如何使用 spring 数据 jpa 中的规范获得最佳结果?

How to get top results using specifications in spring data jpa?

我对 spring 数据 jpa 很陌生。我在查询数据库时尝试使用规范。我的问题是使用 crudrepository 我们可以这样处理:

findTopByUsernameOrderByUpdatedAtDesc(String username);

如何实现相同的使用规范?我可以做一些基本的事情,比如规范中的和或,但不像我们可以用标准等做的那样非常健壮。

Specification<CustomClass> spec = Specifications.where(specification).and(username);
List<CustomClass> list = findAll(spec);

您不能直接在 Specification 中表达。但是您可以为此使用 Pageable

Page oneElementPage = repository.findAll(spec, new PageRequest(0, 1));

给你一个Page只有一个元素。

这是按如下方式完成的:

 Pageable pageable = new PageRequest(0, 1, Sort.Direction.DESC, "username");
 Page oneElementPage = repository.findAll(spec, pageable);

这将按降序对用户名列中的数据进行排序,return 第一个结果。