CriteriaBuilder Many-to-one restriction on id
When doing string based queries it is possible to use the "id" keyword on a many-to-one attribute e.g.:
from Enrolment where person.id=:personId
In this case this would generate sql:
select * from enrolment where person_id=?
How do I achieve the same using the 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(criteriaBuilde开发者_JAVA百科r.equal(root.get("person").root.get("personId"), 1L));
I imagine you could join to person and add a restrict to the person root but that strikes me as overkill.
This worked for me in a similar setup:
criteriaBuilder.equal( datasheetRoot.get( Datasheet_.componentSubtype )
.get( ComponentSubtype_.id ),
componentSubtypeId );
(This is using Spring boot 1.0.1 with Spring Data JPA 1.5.1 and Hibernate 4.3.1)
My root is Datasheet
which has a @ManyToOne
to a ComponentSubtype
which in turn has an id
.
After trial-and-error the following works:
query.where(criteriaBuilder.equal(root.get("person"), 1L));
I guess I have been writing string based queries for so long I couldn't see the wood for the trees. It would be nice if the two ways of writing queries was consistent:
from Enrolement where person=1L (does not work)
精彩评论