Spring数据JPA和可以为null的参数

我的理解是,使用Spring数据JPA我不能有一个查询方法来获取列等于给定的非null方法参数的所有行,并且当method参数为null时,使用相同的方法获取此列为NULL的所有行。

那是对的吗?

所以我必须在我的JAVA代码中区分它,我必须使用一个单独的查询方法明确要求空值,如下例所示?

// Query methods List findByParameter(Parameter parameter); List findByParameterIsNull(); ... List result = new ArrayList(); if (parameter == null) result = findByParameterIsNull(); else result = findByParameter(parameter); 

这很糟糕,如果我有4个参数可以为null并且必须编码16种不同的查询方法。

你是对的。

已经请求支持更好地处理空参数。 https://jira.spring.io/browse/DATAJPA-121

在您的情况下,我建议您编写存储库实现并使用自定义CriteriaQuery来处理您的案例。

您还可以使用带有is null语法的@Query注释:

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

编辑

从Spring数据jpa 2.0开始,spring现在支持@Nullable注释。 这有助于处理传递的null参数。

从文档 :

@Nullable – 用于参数或返回值,可以为null。

似乎Query by Example可能就是您所需要的。

Query by Example是Spring Data中的一个新function( 自 2016年4月发布的Hopper版本 ),它允许用这样的代码创建简单的动态查询

 Person person = new Person(); person.setFirstname("Dave"); ExampleMatcher matcher = ExampleMatcher.matching() .withIncludeNullValues(); Example example = Example.of(person, matcher); personRepository.count(example); personRepository.findOne(example); personRepository.findAll(example); 

方法count/findOne/findAllorg.springframework.data.domain.Example的实例作为参数(其中一些也采用排序/分页参数)来自org.springframework.data.repository.query.QueryByExampleExecutor interface,由org.springframework.data.jpa.repository.JpaRepository扩展org.springframework.data.jpa.repository.JpaRepository interface。

简而言之,所有JpaRepository实例现在都有这些方法。

今天截至2018年6月,通过查看https://jira.spring.io/browse/DATAJPA-121 ,如果您的参数为null,则查询将自动形成为null。

我在我的项目中做到了,这是真的:

 compile group: 'org.springframework.data', name: 'spring-data-jpa', version: '2.0.7.RELEASE' 

 public interface AccountDao extends CrudRepository { //this can accept null and it will become isNull public List findByEmail(String email); } 

如果参数为null:

 select myaccount0_.id as id1_0_, myaccount0_.email as email2_0_, myaccount0_.password as password3_0_, myaccount0_.user_id as user_id4_0_ from my_account myaccount0_ where myaccount0_.email is null 

如果参数不为null:

 select myaccount0_.id as id1_0_, myaccount0_.email as email2_0_, myaccount0_.password as password3_0_, myaccount0_.user_id as user_id4_0_ from my_account myaccount0_ where myaccount0_.email=? 11:02:41.623 [qtp1507181879-72] TRACE ohtype.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - [testing@hotmail.com] 

然后它出现了一个有趣的问题,一些开发人员想要更好的控制来忽略查询中的参数,如果它是null,这仍然在调查https://jira.spring.io/browse/DATAJPA-209 。

我找到了一些东西…如果你把参数放在像这样的jpa方法中

 @Param("value") String value, 

然后它可以为null,在查询中你将具有以下条件:

 (table.value = :value OR :value IS NULL) 

如果值为null,它将自动返回true,如果不为null,它将在表中搜索该值。