加入多个表时如何使用JPA Criteria API [英] How to use JPA Criteria API when joining many tables
问题描述
这是另一个问题:
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Company> criteria = criteriaBuilder.createQuery( Company.class );
Root<Company> companyRoot = criteria.from( Company.class );
Join<Company,Product> products = companyRoot.join("dentist");
Join<Company, City> cityJoin = companyRoot.join("address.city");//Company->Address->City-city
criteria.where(criteriaBuilder.equal(products.get("category"), "dentist"), criteriaBuilder.equal(cityJoin.get("city"),"Leeds"));
一家公司有一个地址,地址里面有 City-pojo 和 Country-Pojo.如何在 JOIN
中使用它?我试图用 address.city
引用它,但我收到错误消息:
A company has an address, inside the address there is City-pojo and Country-Pojo. How can I use it in JOIN
? I tried to reference it with address.city
but I got the error message:
来自托管类型的属性 [address.city][EntityTypeImpl@1692700229:Company [javaType: classcom.test.domain.Company 描述符:RelationalDescriptor(com.test.domain.Company -->[DatabaseTable(COMPANY)]), mappings: 16]] 不存在.
The attribute [address.city] from the managed type [EntityTypeImpl@1692700229:Company [ javaType: class com.test.domain.Company descriptor: RelationalDescriptor(com.test.domain.Company --> [DatabaseTable(COMPANY)]), mappings: 16]] is not present.
推荐答案
如果你使用规范的 Metamodel,您将避免此类错误.在您的代码中,您误用了dentist"关键字,这可能是您出错的原因,因为dentist"不是公司实体中的字段.
If you use canonical Metamodel, you'll avoid this kind of errors. In your code you have misused the "dentist" keyword, that's probably the cause of your error, because "dentist" is not a field in Company entity.
然而,看看你在另一个问题中如何定义你的类,使用元模型定义 join
的方法是这样的:
However, looking at how you defined your class in the other question, the way to define that join
using Metamodel is this:
SetJoin<Company,Product> products = companyRoot.join(Company_.products);
如您所见,Metamodel 避免使用字符串,因此避免了很多运行时错误.如果无论如何你不使用元模型,试试这个:
As you can see, Metamodel avoids the use of strings, and so avoids a lot of runtime errors. If anyway you don't use Metamodel, try this:
SetJoin<Company,Product> products = companyRoot.join("products");
如果你现在想添加一个 predicate
,即在 where
之后的东西,你会写这样的:
If you now want to add a predicate
, i.e. something after the where
, you'll write something like:
Predicate predicate = criteriaBuilder.equal(products.get(Product_.category), "dentist");
criteria.where(predicate);
如果要为 City 实体添加 join
:
If you want to add a join
for the City entity:
Join<Company, City> city = companyRoot.join(Company_.city);
predicate = criteriaBuilder.and(predicate, criteriaBuilder.equal(city.get(City_.cityName), "Leeds");
criteria.where(predicate);
(假设字段 cityName 是您所在城市的正确字段名称).
(supposing that the field cityName is the correct field name for your city).
这篇关于加入多个表时如何使用JPA Criteria API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!