【问题标题】:How to add dynamic sql query in JPA query annotation in spring boot?如何在spring boot的JPA查询注解中添加动态sql查询?
【发布时间】:2019-02-05 09:37:03
【问题描述】:

我想在运行时在查询中添加一个排序列。我已将查询注释用于构建查询。我使用参数“sortCol”在查询中添加排序列。但不知何故,查询注释无法识别“sortCol”帕尔马,因此不使用它。也没有给出任何错误。

 SELECT
        * 
    FROM
        request r 
    WHERE
        r.asset_type IN (
            ?, ?, ?
        ) 
        AND r.request_type IN (
            ?, ?
        ) 
        AND r.status IN  (
            ?, ?, ?, ?
        ) 
        AND r.assign_to = ?  
        AND (
            r.request_custom_id LIKE ? 
            OR r.project_name LIKE ? 
            OR r.asset_type LIKE ? 
            OR r.request_type LIKE ? 
        ) 
    ORDER BY
        ? limit ?"

在此之后,我添加了按列名排序的顺序。在运行时:

    @Query(value ="SELECT * FROM request r WHERE r.asset_type IN (:assetType) AND r.request_type IN (:requestType) AND r.status IN  (:statusList) AND r.assign_to = :assignTo  AND ( r.request_custom_id LIKE %:searchTerm% OR r.project_name LIKE %:searchTerm1% OR r.asset_type LIKE %:searchTerm2% OR r.request_type LIKE %:searchTerm3% ) ORDER BY :sort",nativeQuery = true)
    Page<Request> findRequestdata(Pageable pageable,
            @Param("assetType") List<String> assetType,
            @Param("requestType") List<String> requestType,
            @Param("statusList") List<Integer> statusList,
            @Param("assignTo") Long assignTo,
            @Param("searchTerm") String searchTerm,
            @Param("searchTerm1") String searchTerm1,
            @Param("searchTerm2") String searchTerm2,
            @Param("searchTerm3") String searchTerm3,
            @Param("sort") String sortCol);

除“sortCol”外,所有参数均设置正确。 请建议我在哪里缺少任何东西。

【问题讨论】:

    标签: hibernate spring-boot spring-mvc spring-data-jpa


    【解决方案1】:

    您已经将一个 Pageable 对象传递给您的方法。

    所以在创建分页时还可以添加排序:

    Pageable sortedByName = PageRequest.of(0, 3, Sort.by("name"));
    
    findRequestdata(sortedByName, ...)
    

    在此处阅读更多信息:https://www.baeldung.com/spring-data-jpa-pagination-sorting

    【讨论】:

    • 太棒了!你能接受我的答案是正确的吗?谢谢
    猜你喜欢
    • 2019-07-16
    • 1970-01-01
    • 2017-01-03
    • 2019-07-18
    • 2021-10-13
    • 1970-01-01
    • 2022-01-15
    • 2015-01-27
    • 1970-01-01
    相关资源
    最近更新 更多