【问题标题】:Query database with JPA for null values使用 JPA 查询数据库以获取空值
【发布时间】: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 &amp;&amp; city == null) {...} 等等。
  • 这就是标准 API 或 QueryDSL 存在的原因:动态创建查询。

标签: spring spring-data-jpa jpql


【解决方案1】:

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 字符串或使用 Criteria 创建动态查询也是不错的选择。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    相关资源
    最近更新 更多