如何在连接多个表时使用JPA Criteria API [英] How to use JPA Criteria API when joining many tables

查看:156
本文介绍了如何在连接多个表时使用JPA Criteria API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是另一个问题:

如何在JOIN中使用JPA Criteria API

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:class
com.test.domain.Company descriptor:
RelationalDescriptor(com.test.domain) .Company - >
[DatabaseTable(COMPANY)]),映射: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 ,你将会避免这种错误。
在您的代码中,您滥用了牙医关键字,这可能是导致错误的原因,因为牙医不是公司实体中的字段。

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.

但是,看看你在另一个问题中如何定义你的类,使用Metamodel定义 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避免使用字符串,因此避免了大量的运行时错误。如果你不使用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"); 

如果您现在要添加谓词 ,即在 之后的东西,你会写下这样的东西:

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);

如果你想加一个加入城市实体:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆