Rpj
Rpj

Reputation: 6080

How to return Page instead of List on a JPA query

How to return Page instead of List on the following native JPA query How to handle Pageable as an argument to return a paginated list

@Query(nativeQuery = true, value = "select * from foos where bar_id=:barId")
List<FooBar> findFoosByBarId(Long barId, Pageable pageable);

@Entity
@Table(name = "foo_bars")
public class FooBar {

    @ManyToOne
    Foo foo;
 
    @ManyToOne
    Bar bar;
}

Upvotes: 0

Views: 1760

Answers (1)

frascu
frascu

Reputation: 828

You have to return Page<FooBar> instead of List<FooBar>.

@Query(nativeQuery = true, value = "select * from foos where bar_id=:barId")
Page<FooBar> findFoosByBarId(Long barId, Pageable pageable);

Then you can call the method in this way:

Pageable pageable = PageRequest.of(0, 5, Sort.by(Sort.Direction.DESC, "id"));
Page<FooBar> page = foosRepository.findFoosByBarId(barId, pageable);

On the page variable, uou can call several useful methods:

  • page.getContent() to retrieve the list of elements of the page
  • page.getTotalElements() to get the number of all elements
  • page.getTotalPages() to get the number of pages

Here the other methods of Page class.

Upvotes: 1

Related Questions