JPA ParameterExpression

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)

Consider a situation when the conditional expression for a query is not known at compile time. Some runtime information needs to be passed to the query to get results. We can achieve this using JPQL and criteria api. This article deals with how it can be done using criteria api.

JPA ParameterExpression:

We have seen JPQL. If we wanted to select Teacher entity whose first name is prasad, we can simply write a query as follows.

Here the parameter expression is simply a string value prefixed with a semi-colon. i.e . :firstName. This cannot be done in criteria api. It provides a JPA ParameterExpression for creating a parameter of a specific type.

We have seen introduction to criteria api. Have a look at the code below.

There is only one thing to notice here : ParameterExpression

  • The statement ParameterExpression<String> firstName = cb.parameter(String.class,"firstName");creates a new JPA ParameterExpression of type String which can hold the value of parameter passed afterwards.
  • cb.equal(teacher.get("firstName"), firstName)This works like the t.firstName = :firstName statement in JPQL. Defines the condition for JPA ParameterExpression

Now that we have formed criteria query using JPA ParameterExpression, we can execute it.

 

This prints out information about Teacher entity whose first name is ‘prasad’

Firstname = Prasad Last Name = Kharkar salary = 20000

I hope this articled helped understand JPA ParameterExpressions in criteria api.

 

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.

Leave a Reply

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