且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

加入多个表时如何使用JPA Criteria API

更新时间:2023-09-09 20:44:40

如果你使用规范的 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).