【问题标题】:How to use dynamic query by parameter (native query)如何使用参数动态查询(原生查询)
【发布时间】:2021-12-05 06:38:16
【问题描述】:

下面的代码是我的存储库的一部分。 静态函数不能如下使用,但是我想根据服务接管的参数值接收不同的查询。 你能帮我个忙吗?提前谢谢你。

    @Query(value = " select * " +
            "from t_user usr " +
            "left outer join t_sale_order ord on usr.id = ord.user_idx " +
            "LEFT OUTER JOIN ( " +
                "SELECT " +
                    "sale_order_idx, sum(taxable_amount) + sum(non_taxable_amount) as amount " +
                "FROM t_sale_receipt " +
                "GROUP BY sale_order_idx " +
            ") receipt " +
            "ON receipt.sale_order_idx = ord.id " +
            "where NOT exists ( " +
                "select 1 from t_encourage_sent_list sl " +
                "where sl.user_idx  = usr.id and sl.push_idx = ?1 " +
            ") " +
            "AND NOT EXISTS ( SELECT 1 FROM t_user_study us WHERE us.user_idx = usr.id ) " +
//            readBookCondition(readBook) +
            "AND usr.active = 1", nativeQuery = true)
    List<User> findEncouragePushMsgTarget(Integer pushIdx, Integer readBook);

    static String readBookCondition(Integer readBook) {
        String readBookCondition = "AND NOT EXISTS ( SELECT 1 FROM t_user_study us WHERE us.user_idx = usr.id ) ";
        if ( readBook != null ) return "";
        if ( readBook != 0 ) readBookCondition.replace("NOT", "");
        return readBookCondition;
    }

【问题讨论】:

    标签: spring-boot jpa dynamicquery nativequery


    【解决方案1】:

    您可以使用 JPA 规范编写动态查询。 参考:Spring data JPA Specification

    【讨论】:

    • 我应该如何定义一个不会改变的查询?
    • 您无法通过传递静态 JPA/SQL 查询来定义它相反,您应该调用相应的方法来构造 JPA 查询。 baeldung.com/hibernate-criteria-queries
    【解决方案2】:

    我假设你在if ( readBook != null ) return ""; 中犯了一个错误,它应该是if ( readBook == null ) return ""; 否则它永远不会进入下一个条件if ( readBook != 0 )...

    sql 中方法readBookCondition(readBook) 的等价物是:

    AND NOT EXISTS ( SELECT 1 FROM t_user_study us WHERE us.user_idx = usr.id ) 
    -- start of dynamic part
    AND
        CASE
            WHEN :readBook IS NULL THEN 
                1 = 1
            ELSE 
                CASE 
                    WHEN :readBook != 0 THEN 
                        EXISTS ( SELECT 1 FROM t_user_study us WHERE us.user_idx = usr.id )
                    ELSE 
                        NOT EXISTS ( SELECT 1 FROM t_user_study us WHERE us.user_idx = usr.id )     
                END
        END
    -- end of dynamic part
    AND usr.active = 1;
    

    根据您使用的数据库调整上述内容。

    【讨论】:

      猜你喜欢
      • 2023-01-10
      • 2019-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 2018-08-01
      • 1970-01-01
      • 2014-11-24
      相关资源
      最近更新 更多