CriteriaBuilder对id的多对一限制

时间:2011-03-13 19:09:43

标签: jpa

在进行基于字符串的查询时,可以在多对一属性上使用“id”关键字,例如:

from Enrolment where person.id=:personId

在这种情况下,这将生成sql:

select * from enrolment where person_id=?

如何使用CriteriaBuilder实现相同目标?

CriteriaQuery<Enrolement> query = criteriaBuilder.createQuery(Enrolement.class);
Root<Enrolement> root = query.from(Enrolment.class);
query.select(root);

// Does not work
query.where(criteriaBuilder.equal(root.get("person.id"), 1L));

// Does not work
query.where(criteriaBuilder.equal(root.get("person").root.get("personId"), 1L));

我想你可以加入到一个人身上并为这个人添加一个限制,但这让我觉得有点过分。

2 个答案:

答案 0 :(得分:1)

这对我来说在类似的设置中起作用:

criteriaBuilder.equal( datasheetRoot.get( Datasheet_.componentSubtype )
                                    .get( ComponentSubtype_.id ), 
                       componentSubtypeId );

(这是使用Spring引导1.0.1与Spring Data JPA 1.5.1和Hibernate 4.3.1)

我的根目录是Datasheet,其@ManyToOneComponentSubtype,而id又有{{1}}。

答案 1 :(得分:0)

经过反复试验后,以下方法有效:

query.where(criteriaBuilder.equal(root.get("person"), 1L));

我想我一直在写基于字符串的查询这么长时间我看不到树木。如果编写查询的两种方式是一致的,那就太好了:

from Enrolement where person=1L (does not work)
相关问题