我在三个物体之间有以下关系
public class ProductEntity {
@Id
private int id;
@OneToMany(mappedBy = "productEntity",
fetch = FetchType.LAZY)
private List<ProductInfoEntity> productInfoEntityList = new ArrayList<>();
@Column(name = "snippet")
private String snippet;
}
public class ProductInfoEntity {
@Id
private int id;
@ManyToOne
@JoinColumn(name = "product_id")
private ProductEntity productEntity;
@ManyToOne
@JoinColumn(name = "support_language_id")
private SupportLanguageEntity supportLanguageEntity;
}
public class SupportLanguageEntity {
@Id
private int id;
@Column("name")
private String name;
}
然后,我想制定一个要查询的规范,如下所示:
从product_info中选择* 其中product_id = 1 和support_language_id = 2;
我还在规范中使用注释,这意味着我使用ProductEntity_,ProductInfoEntity_等。
能否请您提供上述查询规范的完整工作代码?
谢谢你们
答案 0 :(得分:2)
要使用Specification,您的ProductInfoEntityRepository
必须扩展JpaSpecificationExecutor
@Repository
public interface ProductInfoEntityRepository
extends JpaRepository<ProductInfoEntity, Integer>, JpaSpecificationExecutor<ProductInfoEntity> {
}
据我了解,您使用JPA
元模型。那么
@Autowired
ProductInfoEntityRepository repository;
public List<ProductInfoEntity> findProductInfoEntities(int productId, int languageId) {
return repository.findAll((root, query, builder) -> {
Predicate productPredicate = builder.equal(
root.get(ProductInfoEntity_.productEntity).get(ProductEntity_.id), // or root.get("productEntity").get("id")
productId);
Predicate languagePredicate = builder.equal(
root.get(ProductInfoEntity_.supportLanguageEntity).get(SupportLanguageEntity_.id), // or root.get("supportLanguageEntity").get("id")
languageId);
return builder.and(productPredicate, languagePredicate);
});
}
如果要使规范可重用,则应创建包含两个静态方法productIdEquals(int)
和languageIdEquals(int)
的实用程序类。
要结合使用它们,请使用Specifications(Spring Data JPA 1. *)或Specification(自Spring Data JPA 2.0起)
答案 1 :(得分:0)
select * from product_info where product_id = 1 and support_language_id = 2;
应按书面规定工作。但是唯一有用的是comment
。
也许您想要所有三个表中的其余信息?
SELECT pi.comment, -- list the columns you need
p.snippet,
sl.name
FROM product AS p -- table, plus convenient "alias"
JOIN product_info AS pi -- another table
ON p.id = pi.product_info -- explain how the tables are related
JOIN support_language AS sl -- and another
ON pi.support_language_id = sl.id -- how related
WHERE p.snippet = 'abc' -- it is more likely that you will start here
-- The query will figure out the rest.
从那里看,是否可以解决JPA提供的混淆。