【发布时间】:2019-05-10 03:23:52
【问题描述】:
数据库中的值有时可能是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", "Bokserska", "xxx", "50-500");
// when
addressRepo.save(address);
// then
assertTrue(addressRepo.testtest("Bokserska")); // OK
测试失败:
// given
address = new Address("WIELKA WARSZAAAWA", null, "xxx", "50-500");
// when
addressRepo.save(address);
// then
assertTrue(addressRepo.testtest(null)); // cuz false!
【问题讨论】:
-
您需要使用
where a.street is null进行查询。 -
但是当
street不为空时,普通查询将不起作用! -
您可以使用多个查询。根据您要查询的内容使用正确的。
-
对于这个例子来说,如果有 12 个 if 会很不舒服...
if(street ==null) {addressRepo.testtest2} ... if(city == null) {..} if(street == null && city == null) {...}等等。 -
这就是标准 API 或 QueryDSL 存在的原因:动态创建查询。
标签: spring spring-data-jpa jpql