11

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?

amorfis
  • 15,390
  • 15
  • 77
  • 125

2 Answers2

8

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();
lloiacono
  • 4,714
  • 2
  • 30
  • 46
Piotr Nowicki
  • 17,914
  • 8
  • 63
  • 82
  • How would yo do it for an element inside a Map? `Path path = entity.get("mapAtribute)...` I don't know how to pass the Key once I get the Map to get the desired Element. Here it is my hole question: http://stackoverflow.com/questions/21436972/jpa-2-criteria-for-sorting-based-on-an-atribute-from-a-map-value Thanks! – Gayolomao Jan 30 '14 at 07:46
1
SELECT e FROM Entity e inner join e.parent p WHERE p.id = :parentId

in criteria call it an Alias like:

sess.createCriteria(Entity.class)
    .createAlias("e.parent", "p")
user000001
  • 32,226
  • 12
  • 81
  • 108
SOMEONE
  • 11
  • 1