Criteria API Path to sub-sub-entity id

amorfis picture amorfis · Nov 30, 2011 · Viewed 7.7k times · Source

I want to transform my JPAQL queries into criteria API queries.

Consider query like this:

SELECT e FROM Entity e WHERE e.parent.id = :parentId

WHERE part is transformed to:

Path<Long> parentId = root.get(Entity_.parent).get(ParentEntity_.id);
Predicate whereParentId = builder.equal(parentId, selectedParent.getId());

The question is, how to create predicate for WHERE like this:

SELECT e FROM Entity e WHERE e.parent.parent.id = :parentId

How to create Path to parent of parent id?

Answer

Piotr Nowicki picture Piotr Nowicki · Dec 3, 2011

If the JPQL you've shown is working, then I'll assume that your ParentEntity is holding a reference to its parent (in a form of parent field of ParentEntity type). Therefore, something like this should work:

Path<Long> parentId = root.get(Entity_.parent)
    .get(ParentEntity_.parent)
    .get(ParentEntity_.id);
Predicate whereParentId = builder.equal(
    parentId, selectedParent.getId()
);

I've done similar thing but for one entity (Customer is child and parent entity at the same time and references its parent through parent field of Customer type) and something like this worked perfectly fine:

query.select(customer)
     .where(criteriaBuilder.equal(
         customer.get("parent").get("parent").get("id"), 
         criteriaBuilder.parameter(int.class, "parentId"))
     );

List<Customer> customers = em.createQuery(query)
    .setParameter("parentId", john.getId()).getResultList();