使用 Spring Data Repository 添加排序到 mongo JSON @Query
我想使用 mongo JSON 查询 并做了一些阅读和实验,我仍然无法让它工作。我有 PagingAndSortingRepository 并可以使用 < findAll 上的 code>Sort() 没有任何问题。
存储库类
public interface ThingRepository extends PagingAndSortingRepository<Thing, ObjectId> {
@org.springframework.data.mongodb.repository.Query("{ name:?0, $or : [ { state:'new' } , {state:'updated'} ] }")
List<Device> findThingsInNewOrUpdatedState(String name);
}
服务层
@Service
public class ThingService() {
@Autowired private ThingRepository thingRepository;
public List<Thing> getSortedThings() {
return (List<Thing>)thingRepository.findAll(new Sort(Sort.Direction.DESC, Arrays.asList("dateModified")));
}
public List<Thing> getNewOrUpdatedThingsSorted() {
return thingRepository.findThingsInNewOrUpdatedState(); // <-- this needs to be sorted
}
}
查询直接转换为 mongoDb 调用,效果很好
db.things.find({ name:'xxx', $or : [ { state:'new' }, {state:'updated'} ] })
,我知道我可以添加 sort()
采用常规 mongoDb 语法,但无法弄清楚该怎么做这是来自 Java/Spring Data 的。它尝试将其添加到 @Query 但它不起作用,因为我认为 Spring 只是执行 <代码>find()。
I want to sort the results of a find
using the mongo JSON query and having done some reading and experimenting, I still can't get it to work. I have got the PagingAndSortingRepository and can use Sort()
on findAll with no problems.
Repository class
public interface ThingRepository extends PagingAndSortingRepository<Thing, ObjectId> {
@org.springframework.data.mongodb.repository.Query("{ name:?0, $or : [ { state:'new' } , {state:'updated'} ] }")
List<Device> findThingsInNewOrUpdatedState(String name);
}
Service layer
@Service
public class ThingService() {
@Autowired private ThingRepository thingRepository;
public List<Thing> getSortedThings() {
return (List<Thing>)thingRepository.findAll(new Sort(Sort.Direction.DESC, Arrays.asList("dateModified")));
}
public List<Thing> getNewOrUpdatedThingsSorted() {
return thingRepository.findThingsInNewOrUpdatedState(); // <-- this needs to be sorted
}
}
The query is translated directly into the mongoDb call, which works fine
db.things.find({ name:'xxx', $or : [ { state:'new' }, {state:'updated'} ] })
and I know I can add a sort()
in regular mongoDb syntax but cannot work out how to do this from within Java/Spring Data. It tried adding it to the @Query but it was not working, since I think Spring is just executing a find()
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该能够简单地向查询方法添加一个
Sort
参数,从而动态地通过管道传入Sort
实例,该实例将应用于@Query< 中定义的查询/代码>。
You should be able to simply add a
Sort
parameter to the query method and thus dynamically pipe inSort
instances that will be applied to the query defined in@Query
.