multiselect in criteria api

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Using multiselect method for selecting multiple expressions is one of the ways from the ways we’ve seen in previous post about tuples This article will deal with multiselect in criteria api.

Multiselect in criteria api:

When you want to only select some specific fields of an entity and not whole entity, multiselect() in criteria api is useful. One thing to note though is that it needs a non – persistent object that can hold the data retrieved by multiselect() query.

We want to retrieve only first name and last name of Teacher entity. So we will create a POJO that can hold the information retrieved by criteria query.

Criteria query for selecting first name and last name is as follows

Note that CriteriaQuery is built for BasicTeacherInfo object and not Teacher object. The statement query.multiselect(teacher.get("firstName"),teacher.get("lastName")); automatically create the constructor expression for BasicTeacherInfo class. After result is retrieved, it is simply iterated and printed out as below

First name = Prasad Last Name = Kharkar
First name = Sushsant Last Name = Pangarkar
First name = Pranil Last Name = Gilda

I hope this example helped understand how multiselect in criteria api works. In next article, we will see how to select multiple expressions using object arrays.

 

References for further study :

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

5 thoughts on “multiselect in criteria api

  • October 1, 2014 at 10:06 pm
    Permalink

    Any idea how do you accomplish this same thing while also using a join ?

    Reply
  • January 3, 2018 at 1:02 pm
    Permalink

    Do we need constructor in result class with specific columns selected in query in the same order?
    Can we do projections in Hibernate 5 without creating constructors for all cush projections list
    like select a, b from c would need C() { a=a, b= b }
    is there any other approach which does not require constructor?

    Reply
  • September 12, 2018 at 5:57 pm
    Permalink

    Extending to @Rameshkumar Ramasamy I want to be able to get different columns with embeded entities. For eg. if I want the employee name from employee table and its role from role table while employee and role are mapped with OneToOne.
    Is there any way in projection when I get employee name and role in one projection call.
    Let me know

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *