Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Criteria Builder Create new Object In Select Statement

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!

like image 414
user1827052 Avatar asked Nov 15 '12 15:11

user1827052


People also ask

How do I create a query in criteria builder?

Use an EntityManager instance to create a CriteriaBuilder object. Create a query object by creating an instance of the CriteriaQuery interface. This query object's attributes will be modified with the details of the query. Set the query root by calling the from method on the CriteriaQuery object.

What is CriteriaQuery?

CriteriaQuery instance is used to create a query object. This query object's attributes will be modified with the details of the query. CriteriaQuery. from method is called to set the query root.

What is CriteriaBuilder in Java?

public interface CriteriaBuilder. Used to construct criteria queries, compound selections, expressions, predicates, orderings. Note that Predicate is used instead of Expression<Boolean> in this API in order to work around the fact that Java generics are not compatible with varags. Since: Java Persistence 2.0.

What is root in criteria query?

For a particular CriteriaQuery object, the root entity of the query, from which all navigation originates, is called the query root. It is similar to the FROM clause in a JPQL query. Create the query root by calling the from method on the CriteriaQuery instance.


1 Answers

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")));
like image 86
Mikko Maunu Avatar answered Oct 19 '22 12:10

Mikko Maunu