[英]How to get top results using specifications in spring data jpa?
I am quite new to spring data jpa.我对 spring 数据 jpa 很陌生。 I am trying to use specifications while querying database.
我试图在查询数据库时使用规范。 My question is using crudrepository we can method like :
我的问题是使用 crudrepository 我们可以使用以下方法:
findTopByUsernameOrderByUpdatedAtDesc(String username);
How can I achieve the same using specifications?我怎样才能达到相同的使用规范? I can do basic things like and or in specifications, but not very robust like we can do with criteria etc.
我可以做一些基本的事情,比如和/或在规范中,但不像我们可以用标准等做的那么健壮。
Specification<CustomClass> spec = Specifications.where(specification).and(username);
List<CustomClass> list = findAll(spec);
This was done as follows :这是按如下方式完成的:
Pageable pageable = new PageRequest(0, 1, Sort.Direction.DESC, "username");
Page oneElementPage = repository.findAll(spec, pageable);
This will sort the data on username column in descending direction and return first result.这将按降序对用户名列上的数据进行排序并返回第一个结果。
You can't express this in a Specification
directly.您不能直接在
Specification
表达这一点。 But you can use a Pageable
for this:但是您可以为此使用
Pageable
:
Page oneElementPage = repository.findAll(spec, new PageRequest(0, 1));
Gives you a Page
with a single element.为您提供一个带有单个元素的
Page
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.