Criteria API select clause : Single selection

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)

Now that we have learned about query roots and path expressions in criteria api, we can look into criteria api select clause. Criteria api select clause can be used to select whole entities, single expression or multiple expressions.

Criteria API select clause

Single selection:

We have seen criteria api select clause query for selecting whole entities. For example, if you want to Select all teachers, then you can build and execute a query as follows:

This returns list of entities of type Teacher which you can later iterate and perform operations.

Consider you want only to select last names of all teachers and don’t want to retrieve whole Teacher entity. We need to select only one field of entity and not whole entity.

For this purpose, we can build the criteria api select clause query as below.

Some points to be noticed here are:

  • We have created a CriteriaQuery of type String and not the entity type Teacher because we want the results to be of type String.
  • Query root remains of Teacher type i.e. Root<Teacher> because we want to query against Teacher entities so we need a query root to access Teacher fields.
  • query.select(teacher.<String>get("lastName")); Notice that we are declaring that we are selecting results of type String in this code.
  • Remember that the type of expression provided to criteria api select clause must be compatible with the result type used to create CriteriaQuery. In our case both are String type.

We have built and executed the query, we can test it out using code below. It will print the last names of all teachers.

This gives results

Kharkar
Pangarkar
Gilda

I hope this example helped understand how single selection can be done using criteria api select clause. In next article we will see how multiple selection can be done using criteria api select clause.

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.

One thought on “Criteria API select clause : Single selection

Leave a Reply

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