繁体   English   中英

jpa:如何检查集合参数是否为空

[英]jpa: how to check collection parameter is null

我的要求是:

  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);

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

考虑将查询拆分为 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 个简单的查询可能比一个复杂的查询更优化。
  • 它独立于数据库。

我不知道如何用 Spring 来做,但这是一个解决方案(没有分页):

@NamedQuery(name="CommodityEntity.searchByCreater", query="select e from CommodityEntity e where (:createrIdsb is null or e.createrEntity.id in :createrIds)")

public List<CommodityEntity> searchByCreater( List<Long> createrIds) {
    return getEntityManager().createNamedQuery("CommodityEntity.searchByCreater", CommodityEntity.class)
        .setParameter("createrIdsb", createrIds == null ? null : 1)
        .setParameter("createrIds", createrIds)
        .getResultList();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM