dev*_*evo 17 jpa spring-data-jpa
我正在使用Spring Data JPA并尝试向我的存储库添加查询.我试图在没有@Query注释的情况下构建查询,如:
List<Item> findByTypeAndStateOrStateAndStartDateBetween(Type type, State s, State s2, Date startDate, Date endDate);
Run Code Online (Sandbox Code Playgroud)
我的目标是构建一个这样的查询:
select * from item where type = ? and (state = ? or state = ?) and start_date between ? and ?
Run Code Online (Sandbox Code Playgroud)
我的问题是OR子句.有没有办法确保有括号?否则,逻辑是不对的.我在这里找到的例子:http: //static.springsource.org/spring-data/data-jpa/docs/1.0.0.M1/reference/html/#jpa.query-methods.query-creation
没有任何或超过1列的子句.
还有,有一种传递对象列表的方法.例如,如果我想找到具有3种状态的项目,我将不得不创建另一个查询,这种查询不能很好地扩展.
谢谢.
编辑:
我想出了如何使用@Query表示法传递状态列表.你这样做:
@Query("FROM item i WHERE i.type = ?1 AND i.state IN (?2)")
Run Code Online (Sandbox Code Playgroud)
然后你可以将列表作为第二个参数传递给方法.如果不使用@Query表示法仍然不知道如何做到这一点.
I wanted to do the same thing with getting all data for a particular station, that was between two dates.
findByStartdateBetweenOrEnddateBetweenAndStation(start,end,start,end,station)
Gives you ==>
SELECT...WHERE (startdate between start,end) OR ( enddatebetween start,end AND station=station)
Run Code Online (Sandbox Code Playgroud)
And:
findByStationAndStartdateBetweenOrEnddateBetween(station, start,end,start,end)
Gives you ==>
SELECT...WHERE (station=station AND startdate between start,end) OR enddatebetween start,end
Run Code Online (Sandbox Code Playgroud)
Both are wrong as I wanted:
SELECT...WHERE station=station AND (startdate between start,end OR enddatebetween start,end)
Run Code Online (Sandbox Code Playgroud)
Use the @Query to be very specific and don't take chances mixing your AND/OR with the method name.
嗯,你们很接近。要执行此操作,无需使用or@Query关键字(不确定在提出问题时是否支持这些关键字):InIsIn
List<Item> findByTypeAndStateInAndStartDateBetween(Type type, Collection<State> states, Date startDate, Date endDate);
Run Code Online (Sandbox Code Playgroud)
In 和 NotIn 还采用 Collection 的任何子类作为参数以及数组或可变参数。对于完全相同的逻辑运算符的其他语法版本,请检查存储库查询关键字。
这足以满足您通过 OR 标准的任意数量的状态的需要。
参考:表 4.查询创建文档中方法名称内支持的关键字
| 归档时间: |
|
| 查看次数: |
11967 次 |
| 最近记录: |