Criteria case expressions

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)

We have learned about case expressions in jpa and what are the benefits provided by it. This article will deal with criteria case expressions.

Criteria case expressions:

In the example given in the article about jpa case expressions our objective was to display salaries in string format which are present as integers in the database. We used Case expression for such condition. JPQL query was as follows.

Now we would like to obtain this result along with the names of teachers using criteria case expressions. Data in database is as below.

3 Prasad Kharkar 20000
4 Sushsant Pangarkar 40000
5 Pranil Gilda 20000

we want to display 20000 as 20k, 40000 as 40k along with teacher name.
Criteria case expressions query is as follows

Points to notice here

  • selectCase() method called on CriteriaBuilder interface works as CASE keyword in JPQL.
  • when() method works as WHEN keyword in JPQL.
  • otherwise() method works as ELSE keyword in JPQL.

We can execute the query using code below.

Retrieving multiples types using object array is explained in generating reports in jpa

This prints out results as follows

Name = Prasad salary = 20k
Name = Sushsant salary = 40k
Name = Pranil salary = 20k

I hope this example helped understand criteria case expressions.

 

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 case expressions

  • March 16, 2016 at 4:50 pm
    Permalink

    when we retrieve result using
    entityManager.createQuery(criteria).getResultList();
    It is not finding appropriate constructor.And we are getting error like–
    org.hibernate.hql.ast.tree.ParameterNode cannot be cast to org.hibernate.hql.ast.tree.SelectExpression
    Do we need any constructor for this.

    Reply

Leave a Reply

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