springspring-bootspring-data-jpajpa-criteria

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


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);

Solution

  • 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.