【发布时间】:2013-09-30 00:06:37
【问题描述】:
在 Spring CrudRepository 中,我们是否支持字段的“IN 子句”?即类似于以下内容?
findByInventoryIds(List<Long> inventoryIdList)
如果没有这样的支持,可以考虑哪些优雅的选择?为每个 id 触发查询可能不是最优的。
【问题讨论】:
标签: java spring jpa spring-data spring-data-jpa
在 Spring CrudRepository 中,我们是否支持字段的“IN 子句”?即类似于以下内容?
findByInventoryIds(List<Long> inventoryIdList)
如果没有这样的支持,可以考虑哪些优雅的选择?为每个 id 触发查询可能不是最优的。
【问题讨论】:
标签: java spring jpa spring-data spring-data-jpa
findByInventoryIdIn(List<Long> inventoryIdList) 应该可以解决问题。
HTTP 请求参数格式如下:
Yes ?id=1,2,3
No ?id=1&id=2&id=3
JPA 存储库关键字的完整列表可以在current documentation listing 中找到。它表明IsIn 是等价的——如果您更喜欢动词以提高可读性——并且JPA 还支持NotIn 和IsNotIn。
【讨论】:
对于 Spring CrudRepository 中的任何方法,您应该能够自己指定 @Query。这样的事情应该可以工作:
@Query( "select o from MyObject o where inventoryId in :ids" )
List<MyObject> findByInventoryIds(@Param("ids") List<Long> inventoryIdList);
【讨论】:
Set<String>作为参数,效果很好。
是的,支持。
查看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);
}
【讨论】: