Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Criteria API Path to sub-sub-entity id

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?

like image 235
amorfis Avatar asked Nov 30 '11 17:11

amorfis


1 Answers

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();
like image 112
Piotr Nowicki Avatar answered Nov 07 '22 12:11

Piotr Nowicki