如何在Spring Data JPA中的值列表的本机查询中使用NVL或COALESCE



我使用如下本机查询,它从多个表中获取数据。我还想根据用户的输入对其进行过滤。用户可以在过滤器菜单中选择"无"、"一个"或"多个"复选框,我的查询将根据这些复选框返回记录。我尝试过两种方法,比如:

src_region.region_id NVL(:regionIds,src_region.region_id )
src_region.region_id in(:regionIds) OR COALESCE (:regionIds)IS NULL)

但对于他们两个,我在发送列表值时都会出现错误。

public interface dbRepository
{
public static final String dbQuery = "select * from
(select src_data.*,
trg_data.*
from
(select reg.region_id,reg.region_name,
ctry.country_id,ctry.country_name
from src_region reg,src_ctry ctry
where reg.region_id=ctry.region_id
AND src_region.region_id in(:regionIds) OR COALESCE (:regionIds)IS NULL) src_data,

(select md.module_id,reg.module_name,
ctry.country_id,ctry.country_name
from trg_module md,trg_ctry ctry
where md.module_id=ctry.country_id
AND ctry.country_id in(:countryIds) OR COALESCE (:countryIds)IS NULL) trg_data
ORDER BY src_data.region_id ";
@Query( value = dbQuery, nativeQuery = true )
List<Object[]> findBySorceOrTarget( @Param( "regionIds" ) List<Long> regionIds, @Param( "countryIds" ) List<Long> countryIds );
}

上的用户可能不发送值。此外,它们也可以只发送一个值,而不是发送多个值。在本机查询中将值列表传递给参数的更好方法是什么?

一般来说,这应该是

AND (src_region.region_id = :regionIds or :regionIds IS NULL)

但是,如果您可以选择多个值,那么=就不好了——您必须切换到in(正如您发布的代码所建议的那样(。但是,你不能这样做,因为你会得到没有结果-你必须将这些值拆分成行。

类似这样的东西(假设:regionIds中的值是逗号分隔的,例如1,2,5:

and (src_region.region_id in (select regexp_substr(:regionIds, '[^,]+', 1, level)
from dual
connect by level <= regexp_count(:regionIds, ',') + 1
)
or :regionIds is null)

最新更新