JPA Case expression

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)

As of now we’ve seen about JPA joins and structure of a simple JPQL statement. JPA 2.0 comes with a JPA case expression which is quite similar to switch statement in java. It enables developer to assign or update the value based on some condition.

JPA Case Expression:

Format of JPA case expression is  as follows

Some points about jpa case expression to notice

  • Most important part of jpa case expression is the WHEN clause.
  • It can have more than one WHEN…THEN clauses.
  • Query processor resolves each expression specified in WHEN clause until it finds a successful one.
  • Successful clauses execute the scalar expression and result is returned.
  • If none of clauses are successful, then ELSE clause is executed.

JPA Case expression example:

Let us continue with the previous data model and consider Teacher entity as follows.

Data in Teacher table in database is as follows.

idTeacher Firstname Lastname salary
4 Sushsant Pangarkar 40000
3 Prasad Kharkar 20000
5 Pranil Gilda 20000

Now, salaries of teachers are in int format but we want them in string format for displaying, how can we do that? We can use jpa case expression as follows.

When this query is being processed and executed,

  • Query processor checks for WHEN clauses and conditional expressions.
  • WHEN t.salary = 20000 THEN '20k' i.e. we are representing 20000 to 20k as string.
  • These conditions will get checked against data in the database and corresponding results will be returned.

When we execute this query as follows.

Results are printed as follows.

Thus, we have represented integer salaries into string format using JPA case expressions.

I hope this articled helped understand jpa 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.

4 thoughts on “JPA Case expression

Leave a Reply

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