简体   繁体   English

如何在Spring数据JPA中的@Query中传递多个查询参数?

[英]How to pass multiple query parameters in @Query in Spring Data JPA?

I am using nativeQuery in my repository which fetches data from multiple tables using join and it also checks for inputs sent by the user within the query.我在我的存储库中使用nativeQuery ,它使用连接从多个表中获取数据,它还检查用户在查询中发送的输入。 My Repository layer looks something like:我的Repository层看起来像:

@Query(
  value = "SELECT e.empname,c.countryName,r.RegionName
  FROM Employee e,Country c, Region r
  WHERE e.countryId=c.countryId
  AND c.regionId=r.regionId
  AND e.employeeId IN (:empIds)
  AND c.countryId IN (:countryIds)
  AND r.regionId IN (:regionIds)", 
  nativeQuery = true)
Collection<Object> findAllActiveUsersNative(CustomFilterRequest request,Pageable pageable);

Following is my filter Class which are lists of IDs sent from the UI and this list properties of class should be sent to query for further filtering.以下是我的过滤器Class ,它们是从 UI 发送的 ID 列表,并且应该将 class 的列表属性发送到查询以进行进一步过滤。

class CustomFilterRequest{
List<Long> empIds,
List<Long> countryIds,
List<Long> regionIds,
}

I know there's @Param which can be used for sending individual query parameters but how to send multiple query parameters as in the scenario mentioned above?我知道有@Param可用于发送单个查询参数,但如何发送多个查询参数,如上述场景? Is there any way to map properties of this class to query parameters in the nativeQuery of @Query ?有没有办法让这个 class 的 map 属性在nativeQuery@Query中查询参数?

If it's not manadatory for you to pass the entire CustomFilterRequest object as a single parameter, how about the following?如果您不强制将整个 CustomFilterRequest object 作为单个参数传递,那么以下如何?

@Query(
  value = "SELECT e.empname,c.countryName,r.RegionName
  FROM Employee e,Country c, Region r
  WHERE e.countryId=c.countryId
  AND c.regionId=r.regionId
  AND e.employeeId IN :empIds
  AND c.countryId IN :countryIds
  AND r.regionId IN :regionIds", 
  nativeQuery = true)
Collection<Object> findAllActiveUsersNative(
  @Param("empIds") List<Long> empIds,
  @Param("countryIds") List<Long> countryIds,
  @Param("regionIds") List<Long> regionIds,
  Pageable pageable);

And then in your service class:然后为您服务 class:

repository.findAllActiveUsersNative(
  customFilterRequest.getEmpIds(),
  customFilterRequest.getCountryIds(),
  customFilterRequest.getRegionIds(),
  pageable);

You can use SpEL expressions .您可以使用SpEL 表达式

  @Query(
      value = "SELECT e.empname,c.countryName,r.RegionName
      FROM Employee e,Country c, Region r
      WHERE e.countryId=c.countryId
      AND c.regionId=r.regionId
      AND e.employeeId IN (:#{#request.empIds})
      AND c.countryId IN (:#{#request.countryIds})
      AND r.regionId IN (:#{#request.regionIds})", 
      nativeQuery = true)
    Collection<Object> findAllActiveUsersNative(CustomFilterRequest request,Pageable pageable);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM