21

I was wondering if it's possible to create such query like :

em.createQuery(
        "SELECT NEW EmpMenu(p.name, p.department.name) "
            + "FROM Project p ").getResultList();

also is it possible to do it via Specification:

public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
        CriteriaBuilder cb) {


    return ???;
}

Thanks in advance!

user1827052
  • 247
  • 1
  • 3
  • 6

1 Answers1

41

Yes, Criteria API does have have construct similar to JPQL constructor expressions. Result class is set via construct method in CriteriaBuilder.

Your JPQL query expressed as an criteria query is:

CriteriaBuilder cb...
CriteriaQuery<EmpMenu> q = cb.createQuery(EmpMenu.class);
  Root<Project> c = q.from(Project.class);
  q.select(cb.construct(EmpMenu.class,
      c.get("name"), c.get("department").get("name")));
Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135
  • 4
    GOOD, It's exactly what i wanted! But now i have another question. I use Spring Data and Specification to create queries. From you example i see that i have to call **q.select** , but in Specification select statement is called automatically (bcs you just return the Predicate). Do I have a chance to do it using Specification interface? or i have to create my own repository, call EntityManage and create the query.... – user1827052 Nov 16 '12 at 08:21
  • Is it possible to specify an Optional value into the construct() method ? like with a LEFT OUTER JOIN, I would like to retrieve in the select a field, and also create the object even if this field is null. – Alex Nov 21 '18 at 13:40
  • 1
    I have a DTO that is composed of few fields, and I recently added a List as a field of this DTO. The criteria builder .construct() was working fine, but I need the select statement to create a List in my custom object. I found nothing on the web about how to do this.. if someone passing by know the answer, ill be grateful, thx – Alex Mar 13 '19 at 09:55
  • Is it possible to set values to list field of custom bean class – PRASANTHMV Jun 28 '19 at 13:59
  • I can't use a custom construct when my entity has a jsonb type field. "Unable to locate appropriate constructor on..." the field type jsonb is replacement by instead a real class. – Hector Mar 27 '20 at 19:28
  • what if list of arguments increase for construct method say above 7. We obviously can't write such a constructor with huge number of arguments for EmpMenu class – harsha kumar Reddy Oct 08 '21 at 11:41
  • @harshakumarReddy use tuple query – Makky Jan 08 '22 at 09:45
  • @Makky if i do that . then again if i want those values in POJO then i have to use loop to initialize those. don't you think its redundant step – harsha kumar Reddy Jan 10 '22 at 05:42
  • @harshakumarReddy thats fine. Its IO process. It won't have any performance issue works a treat though – Makky Jan 14 '22 at 15:42