首页 > 解决方案 > 来自Spring Boot中函数参数的Concat @Query值

问题描述

我们可以通过 QUERY 从字符串中追加 Query 的值吗?如果没有,还有其他选择吗?

注意:需要在页面中返回数据

@Query(nativeQuery = true, value = "从 1=1 的表实体中选择实体" + query + "AND date =:date")

Page getSearchedTable(String query, @Param("date") LocalDate businessDate, Pageable pageable);

标签: javaspring-bootjpaspring-data-jpa

解决方案


您可以使用以下查询来获取可分页数据。记住几点

  1. 您必须在等号和参数之间留出空格,例如 (data = :date)
  2. 不需要给nativeQuery = true,可以使用实体字段
  3. 您不能在 Spring Boot 的本机查询中使用“查询”作为变量。您必须作为参数从服务传递。
  4. 只需在所需查询中传递您的查询参数,如 select 或根据您的请求。下面的例子。

@Query(value = "select entity from table entity where  1=1 AND date = :date AND query = :query")
Page<YourTableEntity> getSearchedTable(@Param("query") String query, @Param("businessDate") LocalDate businessDate, Pageable pageable);

但是,如果您必须强制使用 nativeQuery,那么您可以选择以下任何查询。


1. 第一个选项

 @Query(
      value = "select entity from table entity where  1=1 AND date = :date AND query = :query ORDER BY id", 
      countQuery = "SELECT count(*) FROM table", 
      nativeQuery = true)
      Page<YourTableEntity> getSearchedTable(@Param("query") String query, @Param("businessDate") LocalDate businessDate, Pageable pageable);

2. 第二种选择

@Query(value = "select entity from table entity where  1=1 AND date = :date AND query = :query ORDER BY id \n-- #pageable\n", 
      countQuery = "SELECT count(*) FROM table",
      nativeQuery = true)
      Page<YourTableEntity> getSearchedTable(@Param("query") String query, 
      @Param("businessDate") LocalDate businessDate, Pageable pageable);

推荐阅读