[英]jpa: how to check collection parameter is null
我的要求是:
createrIds
为空,则搜索所有数据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);
该解决方案有两个优点:
我不知道如何用 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.