Spring 使用JPA查询数据库中的空值

Spring 使用JPA查询数据库中的空值,spring,spring-data-jpa,jpql,Spring,Spring Data Jpa,Jpql,数据库中的值有时可以是NULL,有时则不是。我怎样才能找回它? 这是我的尝试,让我感到惊讶: @Repository public interface AddressRepo extends JpaRepository<Address, Long>{ @Query("select count(a) > 0 from Address a where a.street = :street") boolean testtest(@Param("street") St

数据库中的值有时可以是
NULL
,有时则不是。我怎样才能找回它? 这是我的尝试,让我感到惊讶:

@Repository
public interface AddressRepo extends JpaRepository<Address, Long>{

    @Query("select count(a) > 0 from Address a where a.street = :street")
    boolean testtest(@Param("street") String street);
}
测试失败:

// given
address = new Address("WIELKA WARSZAAAWA", null, "xxx", "50-500");
// when
addressRepo.save(address);
// then
assertTrue(addressRepo.testtest(null)); // cuz false!

JPQL无法翻译此语句:

WHERE a.street = null
要创建此SQL,请执行以下操作:

WHERE a.street IS null
因此,您需要创建一个新的
@Query

select count(a) > 0 from Address a where a.street IS NULL

手动挂载JPQL字符串或使用条件创建动态查询也是不错的选择。

您需要使用
进行查询,其中a.street为null
。但是当
street
不为null时,正常查询将不起作用!您可以使用多个查询。根据您想要查询的内容使用正确的一个。对于这个示例,如果有12个ifs,这将非常不舒服<代码>如果(street==null){addressRepo.test2}。。。if(city==null){..}if(street==null&&city==null){…}etc。这就是存在criteriaapi或QueryDSL的原因:动态创建查询。
select count(a) > 0 from Address a where a.street IS NULL