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?
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.
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.
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.
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);
}
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With