My understanding is, that with Spring data JPA I cannot have a query method to fetch all rows where a column equals a given non-null method parameter and use the same method to fetch all rows where this column is NULL when the method parameter is null.
Is that correct?
So I have to distinguish this in my JAVA code and I must use a separate query method explicitly asking for null values, like in the example below?
// Query methods
List<Something> findByParameter(Parameter parameter);
List<Something> findByParameterIsNull();
...
List<Something> result = new ArrayList<>();
if (parameter == null)
result = findByParameterIsNull();
else
result = findByParameter(parameter);
That's bad, if I have 4 parameters which could be null and would have to code 16 different query methods.
It seems Query by Example might be what you need.
Query by Example is a new feature in Spring Data (since version Hopper, out April 2016), which allows one to create simple dynamic queries with a code like this
Methods
count/findOne/findAll
that take an instance oforg.springframework.data.domain.Example
as a parameter (and some of them also take sorting/pagination parameters) are coming fromorg.springframework.data.repository.query.QueryByExampleExecutor<T>
interface, which is extended byorg.springframework.data.jpa.repository.JpaRepository<T, ID extends Serializable>
interface.In short, all
JpaRepository
instances now have these methods.i found something...if u put the parameter in the jpa method like this
then it can be null and in the query you will have this condition:
if the value is null it will automatically return true and if is not null, it will search that value in the table.
Today as of Jun 2018, by looking at https://jira.spring.io/browse/DATAJPA-121, the query will automatically form
is null
if your parameter is null.I did that in my project, it is true:
--
if parameter is null:
if parameter is not null:
Then it comes to an interesting question, some developers want better control to ignore the parameter in query if it is null, this is still being under investigating in https://jira.spring.io/browse/DATAJPA-209.
You are right.
A request has been made to support better handling of null parameters. https://jira.spring.io/browse/DATAJPA-121
In your case, i would advise you to write your repository implementation and to use a custom CriteriaQuery to handle your case.
Also you can use the @Query annotation with the is null syntax :
EDIT
Since Spring data jpa 2.0, spring now supports @Nullable annotation. This can be helpful to handle null parameters passed.
From the documentation :