Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a Page of DTO objects from Spring Data repository

I'm trying to use DTOs in a Spring project to decouple business and presentation but I'm having problems while retrieving data from the Spring Data repository. Here I have a sample code:

public Page<UserDto> findAll(int pageIndex) {
    return userRepository.findAll(createPageable(pageIndex)); // Page<User>
}

As you can see, I'm trying to return a page of UserDto but I'm getting a page of User.

How can I do this?

like image 441
David Moreno García Avatar asked Dec 18 '14 23:12

David Moreno García


People also ask

How do I get DTO from JPA repository?

Interface-based DTO projections You first need to define an interface that defines a getter method for each attribute your projection shall contain. At runtime, Spring Data JPA then generates a class that implements that interface. You can then use that interface as the return type of a repository method.

Should I use JpaRepository or CrudRepository?

Crud Repository doesn't provide methods for implementing pagination and sorting. JpaRepository ties your repositories to the JPA persistence technology so it should be avoided. We should use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.

What is difference between PagingAndSortingRepository and JpaRepository?

PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.


2 Answers

Since Spring-Data 1.10 you can use the Page#map function:

public Page<UserDto> findAll(Pageable p) {
    return userRepository.findAll(p).map(UserConverter::convert);
}

See Spring Data. The UserConverter#convert method takes a Person and converts it to PersonDto.

public PersonDto convert(Person person) {
    return new PersonDto(person.getXyz1(), person.getXyz2);
}
like image 82
andrewinkler Avatar answered Sep 26 '22 08:09

andrewinkler


You can do it like this :

public Page<UserDto> findAll(Pageable p) {
    Page<User> page = userRepository.findAll(p); // Page<User>
    return new PageImpl<UserDto>(UserConverter.convert(page.getContent()), p, page.getTotalElements());
}
like image 26
lusoAlex Avatar answered Sep 26 '22 08:09

lusoAlex