selecting multiple expressions using tuples

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)

Continuing with our examples from previous article about criteria api select clause. We will move further to see selecting multiple expressions using tuples can be done in criteria api.

Selecting multiple expressions using tuples:

We have seen how we can generate reports in jpa using jpql. We can do similar thing using criteria api by selecting multiple expressions in select clause. This can be done by various ways

  • Using Tuples
  • Using non-persistent classes
  • Using arrays of objects.

 

selecting multiple expressions depends upon what we are passing as argument to select() method in criteria api.

ResultType Argument to select() method
Tuple CompoundSelection<Tuple>
Non-persistent class CompoundSelection<T>
Array of objects CompoundSelection<Object[]>

Selecting multiple expressions using tuples

Consider we want to select only first name and last name of teacher entity. The JPQL for it would be

Similar result can be obtained by selecting multiple expressions in the form of Tuple as below.

Points to notice about the code above are:

  • CriteriaQuery<Tuple> query = cb.createTupleQuery(); This creates a CriteriaQuery of type tuple using createTupleQury() method of CriteriaBuilder. We should pass CompoundSelection<Tuple> to select method.
  • cb.tuple(teacher.get("firstName"), teacher.get("lastName")) This creates a compound valued selection item by selecting multiple expressions using tuples
  • The for loop then iterates the results and extracts results from each tuple.

 

This will print results as follows:

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 selecting multiple expressions using tuples can be achieved in criteria api. In upcoming articles, we will see other ways to do the same.

 

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.

2 thoughts on “selecting multiple expressions using tuples

Leave a Reply

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