Java Spring CrudRepository findByInventoryIds(List<Long>inventoryIdList) - 相当于 IN 子句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18987292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause
提问by Espresso
In Spring CrudRepository, do we have support for "IN clause" for a field? ie something similar to the following?
在 Spring CrudRepository 中,我们是否支持字段的“IN 子句”?即类似于以下内容?
findByInventoryIds(List<Long> inventoryIdList)
If such support is not available, what elegant options can be considered? Firing queries for each id may not be optimal.
如果没有这样的支持,可以考虑哪些优雅的选择?为每个 id 触发查询可能不是最佳的。
采纳答案by Oliver Drotbohm
findByInventoryIdIn(List<Long> inventoryIdList)
should do the trick.
findByInventoryIdIn(List<Long> inventoryIdList)
应该做的伎俩。
The HTTP request parameter format would be like so:
HTTP 请求参数格式如下:
Yes ?id=1,2,3
No ?id=1&id=2&id=3
The complete list of JPA repository keywords can be found in the current documentation listing. It shows that IsIn
is equivalent – if you prefer the verb for readability – and that JPA also supports NotIn
and IsNotIn
.
可以在当前文档列表中找到 JPA 存储库关键字的完整列表。它表明这IsIn
是等效的 - 如果您更喜欢可读性的动词 - 并且 JPA 也支持NotIn
和IsNotIn
。
回答by digitaljoel
For any method in a Spring CrudRepository you should be able to specify the @Query yourself. Something like this should work:
对于 Spring CrudRepository 中的任何方法,您应该能够自己指定 @Query。这样的事情应该工作:
@Query( "select o from MyObject o where inventoryId in :ids" )
List<MyObject> findByInventoryIds(@Param("ids") List<Long> inventoryIdList);
回答by Dzinot
Yes, that is supported.
是的,这是支持的。
Check the documentation provided herefor the supported keywords inside method names.
检查此处提供的文档以了解方法名称中支持的关键字。
You can just define the method in the repository interface without using the @Queryannotation and writing your custom query. In your case it would be as followed:
您可以只在存储库接口中定义方法,而无需使用@Query注释和编写自定义查询。在您的情况下,它将如下所示:
List<Inventory> findByIdIn(List<Long> ids);
I assume that you have the Inventoryentity and the InventoryRepositoryinterface. The code in your case should look like this:
我假设您有Inventory实体和InventoryRepository接口。您的案例中的代码应如下所示:
The Entity
实体
@Entity
public class Inventory implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
// other fields
// getters/setters
}
The Repository
存储库
@Repository
@Transactional
public interface InventoryRepository extends PagingAndSortingRepository<Inventory, Long> {
List<Inventory> findByIdIn(List<Long> ids);
}