【问题标题】:How to use NVL or COALESCE in native query for list of values in Spring Data JPA如何在本机查询中使用 NVL 或 COALESCE 获取 Spring Data JPA 中的值列表
【发布时间】:2022-01-16 17:24:35
【问题描述】:

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

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

}

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

【问题讨论】:

    标签: sql oracle spring-boot hibernate spring-data-jpa


    【解决方案1】:

    一般来说应该是这样

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

    但是,如果您可以选择多个值,那么 = 就不行了 - 您必须切换到 in(正如您发布的代码所暗示的那样)。但是,您不能这样做,因为您将得到 nothing 作为结果 - 您必须将这些值拆分为行。

    类似这样(假设: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)
    

    【讨论】:

      猜你喜欢
      • 2016-09-30
      • 2021-01-11
      • 1970-01-01
      • 2019-06-21
      • 1970-01-01
      • 1970-01-01
      • 2021-03-25
      • 2014-12-02
      • 2019-07-26
      相关资源
      最近更新 更多