【问题标题】:jpa: how to check collection parameter is nulljpa:如何检查集合参数是否为空
【发布时间】:2016-03-28 12:41:17
【问题描述】:

我的要求是:

  1. 如果createrIds 为空,则搜索所有数据
  2. 如果createrIds 不为空,则匹配数据

以下代码不起作用,我该如何解决?

@Query("from CommodityEntity e where (:createrIds is null or e.createrEntity.id in :createrIds)" )
Page<CommodityEntity> searchByCreaterAndPage( @Param("createrIds") List<Long> createrIds,Pageable pageable);

【问题讨论】:

  • 请描述您使用当前代码遇到的错误。
  • 这是生成的 sql::createrIds_0_, :createrIds_1_, :createrIds_2_, :createrIds_3_ IS NULL OR e.createrEntityId IN :createrIds_0_, :createrIds_1_, :createrIds_2_, :createrIds_3_
  • JPQL 应该以“SELECT e”开头。还要将 ":createrIds" 放在括号 "(:createrIds)" 中,因为一些 JPA 实现需要它(尽管其他实现不需要)

标签: java jpa hql jpql


【解决方案1】:

我在 (coalesce(:createrIds, null) is null or e.createrEntity.id in (:createrIds)) 上取得了成功,但是否可行可能取决于您使用的数据库。

【讨论】:

  • 遗憾的是,这不适用于 db2... 但 (coalesce(:createrIds, '') = '' or e.createrEntity.id in (:createrIds)) 只要集合不为空(必须为 null 或具有值)就可以使用
【解决方案2】:

考虑将查询拆分为 2 个不同的较小查询,并在接口中使用 default 关键字来实现检查:

default Page<CommodityEntity> searchByCreaterAndPage( @Param("createrIds") List<Long> createrIds,Pageable pageable) {
    if (createrIds == null || createrIds.isEmpty()) {
        return searchAllByPage(pageable);
    } else {
        return searchByNonNullCreaterAndPage(createrIds, pageable);
    }
}

@Query("from CommodityEntity e where e.createrEntity.id in :createrIds" )
Page<CommodityEntity> searchByNonNullCreaterAndPage(@Param("createrIds") List<Long> createrIds, Pageable pageable);

@Query("from CommodityEntity e" )
Page<CommodityEntity> searchAllByPage(Pageable pageable);

此解决方案有 2 个优点:

  • 2 个简单的查询可能比一个复杂的查询更优化。
  • 它独立于数据库。

【讨论】:

  • 你应该检查createrIds == null || createrIds.isEmpty()...如果传递一个空列表,查询很可能会爆炸
猜你喜欢
  • 2018-12-24
  • 2017-05-07
  • 2018-08-09
  • 1970-01-01
  • 2011-04-24
  • 2016-06-20
  • 2017-05-28
  • 2019-07-20
  • 1970-01-01
相关资源
最近更新 更多