Query with sort() and limit() in Spring Repository interface

ぐ巨炮叔叔 提交于 2019-11-27 19:28:32
Oliver Drotbohm

What's wrong with:

public interface JobRepository extends MongoRepository<Job, String> {

  @Query("{ state : 'ACTIVE' }")
  Page<Job> findOneActiveOldest(Pageable pageable);
}

and using it:

// Keep that in a constant if it stays the same
PageRequest request = new PageRequest(0, 1, new Sort(Sort.Direction.DESC, "created"));
Job job = repository.findOneActiveOldest(request).getContent().get(0);
Marc

Just adding a correction to Oliver's answer, it's Direction.DESC and not Directions.DESC and the order of the params is wrong.

Change :

PageRequest request = new PageRequest(0, 1, new Sort("created", Directions.DESC));

to:

PageRequest request = new PageRequest(0, 1, new Sort(Direction.DESC, "created"));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!