【问题标题】:Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clauseSpring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - 相当于 IN 子句
【发布时间】:2013-09-30 00:06:37
【问题描述】:

在 Spring CrudRepository 中,我们是否支持字段的“IN 子句”?即类似于以下内容?

 findByInventoryIds(List<Long> inventoryIdList) 

如果没有这样的支持,可以考虑哪些优雅的选择?为每个 id 触发查询可能不是最优的。

【问题讨论】:

    标签: java spring jpa spring-data spring-data-jpa


    【解决方案1】:

    findByInventoryIdIn(List&lt;Long&gt; inventoryIdList) 应该可以解决问题。

    HTTP 请求参数格式如下:

    Yes ?id=1,2,3
    No  ?id=1&id=2&id=3
    

    JPA 存储库关键字的完整列表可以在current documentation listing 中找到。它表明IsIn 是等价的——如果您更喜欢动词以提高可读性——并且JPA 还支持NotInIsNotIn

    【讨论】:

    • 谢谢,这正是我想要的。他们是否将其记录在 CrudRepository 页面中,或者通过阅读代码发现?
    • 谢谢。那个“宝石隐藏在附录 B 中”,这是正确的 :)
    • Reference docs 网址已更改
    • 对于方法签名:List findByIdIn(List ids);我收到错误消息:原因:java.lang.NumberFormatException:对于输入字符串:“(1, 2)”
    【解决方案2】:

    对于 Spring CrudRepository 中的任何方法,您应该能够自己指定 @Query。这样的事情应该可以工作:

    @Query( "select o from MyObject o where inventoryId in :ids" )
    List<MyObject> findByInventoryIds(@Param("ids") List<Long> inventoryIdList);
    

    【讨论】:

    • 谢谢,这行得通。正在寻找“更清洁”的解决方案,即不编写 @Query。
    • Oliver Gierke 是知道这个问题的答案的人,他有“更清洁”的解决方案。你应该接受他的回答。
    • 太棒了!我用了Set&lt;String&gt;作为参数,效果很好。
    • 如果我想将 2 个参数传递给我的方法一个 list 和另一个普通 string ,那会起作用吗?如果是,我该如何命名我的方法
    【解决方案3】:

    是的,支持。

    查看here 提供的文档,了解方法名称中支持的关键字。

    您可以只在存储库接口中定义方法,而无需使用 @Query 注释并编写自定义查询。在您的情况下,如下所示:

    List<Inventory> findByIdIn(List<Long> ids);
    

    我假设您有 Inventory 实体和 InventoryRepository 接口。您案例中的代码应如下所示:

    实体

    @Entity
    public class Inventory implements Serializable {
    
      private static final long serialVersionUID = 1L;
    
      private Long id;
    
      // other fields
      // getters/setters
    
    }
    

    存储库

    @Repository
    @Transactional
    public interface InventoryRepository extends PagingAndSortingRepository<Inventory, Long> {
    
      List<Inventory> findByIdIn(List<Long> ids);
    
    }
    

    【讨论】:

    • 这适用于所有扩展 CrudRepository 接口的接口。
    • 如果 ids 大小超过 1000 或特定大小取决于 DB,这将不起作用。这个怎么样? List findByIdIn(List ids, Pageable pageable);
    猜你喜欢
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-22
    • 1970-01-01
    相关资源
    最近更新 更多