Criteria Query

Published On: 30 December 2022.By .
  • General

Queries are the methods that finds the information from the database and these methods are written inside the interface.

Query Creation from method names

We have User Model with the attributes :

Now if we have to find the user by firstname or we have to find the list of user with given price, for that we have to write the query but we have some JPA methods to find these. So no need to write query, just simply declare the methods.

You can see this article of spring.io for more details.

Why we need Specification ?

In the Query creation from method names we have to write method query or query for every new demand. So,

  • it is not reusable
  • keeping track of all methods is difficult

That’s why we need specification because it is reusable.

Spring JPA Specifications is a great tool whether we want to create reusable predicates or want to generate typesafe queries programmatically.

In the service class we create method whose return type is specification and it overrides a toPredicate method which accepts the 3 parameter.

In the controller, we call the findAll method of userRepository and pass the specification in that.

Here the Request method is post because we have to pass the values for searching and sometimes the values can be large. So we have to use the POST method.

Now If we want to pass multiple list of Criteria Query then we can return lambda function.

We can also write like, equal, in, between, join, and many more operators as we use in the SQL Query.

Output :

In this way we can use Criteria API. It offers a programmatic way to create typed queries, which helps us avoid syntax errors.

Related content

That’s all for this blog

Go to Top