Spring Data JPA: Filter by one Field, sort by another field and get first

Viewed 401

Let's say have a table with the following columns: STATUS - SUBMITTED - USER_ID

I would like query the repository interface in order to get the row that was SUBMITTED last by a certain USER_ID.

I know there is findByUserId(long userId) and findFirstByOrderBySubmittedDesc(), but I have no clue how to combine them.

How do I combine these two methods?

2 Answers

Okay I figured it out by trial and error:

findFirstByUserIdOrderBySubmittedDesc(long userId)

Maybe this is helps someone :)

In your repo define a method:

Page<YourEntity> findByUserId(Long userId, Pageable page)

Call it like this. Create a Pageable:

Pageable firstBySubmittedDescending = 
  PageRequest.of(0, 1, Sort.by("submitted").descending());

Pass it to your method.

Remember you get a Page not one entity. You need to call getContent() on the page to get it.

Related