3

I am quite new to spring data jpa. I am trying to use specifications while querying database. My question is using crudrepository we can method like :

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);
Nakul Kumar
  • 325
  • 1
  • 5
  • 11

2 Answers2

3

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.

Markus Pscheidt
  • 6,853
  • 5
  • 55
  • 76
Nakul Kumar
  • 325
  • 1
  • 5
  • 11
1

You can't express this in a Specification directly. But you can use a Pageable for this:

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

Gives you a Page with a single element.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348