Spring数据JPA和可以为null的参数 [英] Spring data JPA and parameters that can be null
问题描述
我的理解是,使用Spring数据JPA我不能有一个查询方法来获取列等于给定的非null方法参数的所有行,并使用相同的方法来获取此列为NULL的所有行参数为null。
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.
这是正确的吗?
所以我必须在我的JAVA代码中区分它必须使用一个单独的查询方法显式询问空值,如下例所示?
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);
这很糟糕,如果我有4个参数可以为null并且必须编码16种不同的查询方法。
That's bad, if I have 4 parameters which could be null and would have to code 16 different query methods.
推荐答案
你是对的。
已提出请求支持更好地处理null参数。
https://jira.spring.io/browse/DATAJPA-121
A request has been made to support better handling of null parameters. https://jira.spring.io/browse/DATAJPA-121
在您的情况下,我建议您编写存储库实现并使用自定义 CriteriaQuery 来处理你的案子。
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 :
@Query("[...] where :parameter is null"
public List<Something> getSomethingWithNullParameter();
编辑
自Spring数据jpa 2.0,spring现在支持@Nullable注释。这可以提供帮助处理传递的null参数。
Since Spring data jpa 2.0, spring now supports @Nullable annotation. This can be helpful to handle null parameters passed.
来自文档:
@Nullable - to用于参数或返回值可以为null。
@Nullable – to be used on a parameter or return value that can be null.
这篇关于Spring数据JPA和可以为null的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!