Spring数据JPA和可以为空的参数 [英] Spring data JPA and parameters that can be null

查看:30
本文介绍了Spring数据JPA和可以为空的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是,使用 Spring 数据 JPA,我无法使用查询方法来获取列等于给定非空方法参数的所有行,并使用相同的方法获取该列为 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.

推荐答案

你说得对.

已提出请求以支持更好地处理空参数.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.

您也可以使用 @Query 带有 为空 语法:

Also you can use the @Query annotation with the is null syntax :

@Query("[...] where :parameter is null"
public List<Something> getSomethingWithNullParameter();

编辑

从 Spring data jpa 2.0 开始,spring 现在支持 @Nullable 注解.这有助于处理传递的空参数.

Since Spring data jpa 2.0, spring now supports @Nullable annotation. This can be helpful to handle null parameters passed.

来自文档 :

@Nullable – 用于可以为 null 的参数或返回值.

@Nullable – to be used on a parameter or return value that can be null.

这篇关于Spring数据JPA和可以为空的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆