Reputation: 667
Consider a table with 4 fields: id, name, age, date. Now I want to look up the Database using these fields. So that's simple, I can do:
@Query("select d from data d where d.name=:name and d.age=:age and d.date=:date")
But the problem is, name, age and date are optional fields, i.e age, name, the date can be null. If age is null, then I should look up the Database using name and date and if age and name are NULL, then I should look up the Database using the date alone and so on...
Is it possible to achieve this in a simple way rather than forming different queries for each scenario? Because the real scenario that I am working on has 6-7 optional fields and forming different queries for each one looks damn weird.
Upvotes: 6
Views: 18613
Reputation: 463
For optional field, use this:
@Query("select d from data d
where (:name is null or d.name=:name)
and (:age is null or d.age=:age)
and (:date is null or d.date=:date)")
Upvotes: 16
Reputation: 1253
This is a very common requirement where we want a hibernate query result based on search parameters or custom conditions.
After the introduction of JPA, it is hard to write such a query.
But there is a way by which you can create custom queries based on conditions.
Use EntityManager which will help you to execute HQL and Native query and your further implementation will remain the same. Declare EntityManager object in your implementation and then use its methods to get data based on a query,
@PersistenceContext
EntityManager entityManager;
Execute your query:
entityManager
.createQuery(queryString);
An important point: If you have a requirement for pagination then It will not give you the total record count which you can easily get in a JPA Page object by calling its getTotalElements() method. In this implementation, if you need the total count also then you have to call a separate query for the count.
Review detail example: Add Custom Functionality to a Spring Data Repository
Upvotes: 0