如何在 Spring Data Rest 的 JPA 查询中使用列表参数?

How to use list parameter in JPA query with Spring Data Rest?

@Query("Select loc from Location loc where loc in :locations"
    )
    public Page<Location> searchLocations(List<Location> locations,
                                 Pageable pageable);

然后当使用

调用端点时
https://localhost:8080/api/v1/stores/search/searchLocations?locations=https://localhost:8080/api/v1/locations/23,https://localhost:8080/api/v1/locations/24

只返回 24,而不是 23。

您实际上是如何向 JPA 查询提供列表参数的?

根据 可变参数开箱即用(如果您避免使用 Pageable 参数)。因为数组和可变参数几乎相同,而且您还想将 Pageable 传递给方法,所以我尝试使用数组:

您可以将参数更改为 Location[] locations 以便签名如下所示:

@Query("Select loc from Location loc where loc in :locations")
public Page<Location> searchLocations(Location[] locations, Pageable pageable);

有了这个,您就可以按照@alan-hay 在他的评论中提到的方式调用端点:

curl -X GET "https://localhost:8080/api/v1/stores/search/searchLocations?locations=https://localhost:8080/api/v1/locations/24&locations=https://localhost:8080/api/v1/locations/23"

这里有一些 SQL 输出以显示执行的内容:

Hibernate: select location0_.id as id1_0_ from location location0_ where location0_.id in (? , ?) limit ?

备注

因为您可以通过自己的端点 (http://localhost:8080/api/v1/locations/{locationId}) 访问位置,所以位置本身可能有一个额外的 (Spring Data Rest) 存储库。在这种情况下,这也是可能的:

public interface LocationRepository extends JpaRepository<Location, Long> {
  // Here you are also able to use Long[] instead of List<Long>
  public Page<Location> findByIdsIn(List<Long> ids, Pageable pageable);
}

有了它,您可以像这样搜索存储库

curl -X GET "https://localhost:8080/api/v1/locations/search/findByIdsIn?ids=24,23"