【问题标题】:How to use list parameter in JPA query with Spring Data Rest?如何使用 Spring Data Rest 在 JPA 查询中使用列表参数?
【发布时间】:2021-03-25 15:18:39
【问题描述】:
@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 查询提供列表参数?

【问题讨论】:

  • 你试过了吗:locations=https://localhost:8080/api/v1/locations/23&amp;locations=https://localhost:8080/api/v1/locations/24
  • 刚试过。同样的问题
  • 我知道这适用于 QueryDsl 扩展。不知道你有没有看过。 Essentailly 将为您提供开箱即用的查询功能,而无需在存储库中创建搜索方法。不回答,但也许值得一看....
  • 你是限制使用List&lt;Location&gt;还是可以切换到数组Location[]
  • 数组没问题,只要有办法调用端点

标签: spring-boot jpa spring-data spring-data-rest


【解决方案1】:

根据https://stackoverflow.com/a/48504735/2201165,可变参数开箱即用(如果您要避免使用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"

【讨论】:

    猜你喜欢
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 2014-12-02
    • 1970-01-01
    • 2015-01-12
    • 2016-02-27
    • 1970-01-01
    相关资源
    最近更新 更多