Spring JPA数据"OR"询问 [英] Spring JPA Data "OR" query

查看:88
本文介绍了Spring JPA数据"OR"询问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring Data JPA并尝试向我的存储库添加查询.我试图只构建没有@Query注释的查询,例如:

I am using Spring Data JPA and trying to add a query to my repository. I was trying to just build the query without the @Query annotation like:

List<Item> findByTypeAndStateOrStateAndStartDateBetween(Type type, State s, State s2, Date startDate, Date endDate);

我的目标是建立一个像这样的查询:

My goal is to build a query like so:

select * from item where type = ? and (state = ? or state = ?) and start_date between ? and ?

我的问题是OR子句.有没有办法确保有括号?否则,逻辑是不正确的.我在这里找到的示例: http://static.springsource.org/spring-data/data-jpa/docs/1.0.0.M1/reference/html/#jpa.query-methods.query-creation

My problem is with the OR clause. Is there a way to make sure there are brackets? Otherwise, the logic isn't right. The examples I found here: http://static.springsource.org/spring-data/data-jpa/docs/1.0.0.M1/reference/html/#jpa.query-methods.query-creation

没有任何or条款超过1列.

don't have any or clauses with more than 1 column.

此外,还有一种方法可以传递对象列表.例如,如果我想查找3种状态的商品,则必须创建另一个查询,该查询的伸缩性不是很好.

Also, is there a way to pass in a List of objects. For instance, if I wanted to find items with 3 states I would have to create another query, which doesn't scale very well.

谢谢.

我想出了如何使用@Query表示法传递状态列表.您可以这样操作:

I figured out how to pass of list of states using the @Query notation. You do it like so:

@Query("FROM item i WHERE i.type = ?1 AND i.state IN (?2)")

然后,您可以将列表作为第二个参数传递给该方法.仍然不知道如何使用@Query表示法.

Then you can just pass in a list to the method as the second parameter. Still don't know how to do this without using the @Query notation.

推荐答案

嗯,您非常亲密.要在没有@Query的情况下执行此操作,可以使用InIsIn关键字(不确定在提出问题时是否支持这些关键字):

Well, you are very close. To do this without @Query the In or IsIn keyword can be used(not sure whether these keywords were supported at the time the question was asked):

List<Item> findByTypeAndStateInAndStartDateBetween(Type type, Collection<State> states, Date startDate, Date endDate);

In和NotIn也将Collection的任何子类也作为参数 作为数组或varargs.对于其他相同的句法版本 逻辑运算符检查存储库查询关键字.

In and NotIn also take any subclass of Collection as parameter as well as arrays or varargs. For other syntactical versions of the very same logical operator check Repository query keywords.

这将满足您为OR条件传递任何数量的州的需求.

This will suffice your need of passing any number of states for the OR criteria.

参考:表4. 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆