Convert <Entity> page to PageDTO <EntityDTO>

I am using JPA spring data.

my controller is as follows

    @RequestMapping(value = "/pages/{pageNumber}", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Page<User>> paginatedUser(@PathVariable final Integer pageNumber)
    {
        final PageRequest request = new PageRequest(pageNumber - 1, DEFAULt_PAGE_SIZE, Sort.Direction.DESC, "startTime");
        return new ResponseEntity<>(userRepository.findAll(request), HttpStatus.OK);
    }

Now I decided to send a PageDTO object instead of a Page object to restrict the objects from sending. Can I convert a page to PageDTO using java 8.

I saw that the page is retrieved from Iterable. So I think I can do something like the following, but I'm not sure how to put it together with PageDTO and UserDTO.

StreamSupport.stream(userRepository.findAll(request).spliterator(),false)

is there any efficient java 8 way to do this.

I came up with this solution

     @RequestMapping(value = "/pages/{pageNumber}", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
     public ResponseEntity<PageDTO> paginatedUser(@PathVariable final Integer pageNumber)
        {
            final PageRequest request = new PageRequest(pageNumber - 1, DEFAULt_PAGE_SIZE, Sort.Direction.DESC, "startTime");
            final Page<User> page = userRepository.findAll(request);
            return new ResponseEntity<>(new PageDTO(page, StreamSupport.stream(page.getContent().spliterator(), true).map(UserDTO::new)
                    .collect(Collectors.toList())), HttpStatus.OK);
        }


public class PageDTO {

    private int beginIndex;

    private int currentIndex;

    private int endIndex;

    private List<?> entities;

    public PageDTO(final Page<?> page, final List<?> entities) {
        this.entities = entities;
        this.currentIndex = page.getNumber() + 1;
        this.beginIndex = Math.max(1, currentIndex - 5);
        this.endIndex = Math.min(beginIndex + 10, page.getTotalPages());
    }

I would like to know if there is another effective way to do this?

+4
source share
1 answer

, , , , . , : https://github.com/pkainulainen/spring-data-jpa-examples/blob/master/query-methods/src/main/java/net/petrikainulainen/springdata/jpa/todo/TodoMapper.java

JpaRepository, , DTO ( , ..), :

@Repository
public interface Repository extends JpaRepository<Entity, Integer> {

    /**
     * Name the method according to what query you need to execute
     * e.g. findAll --> return all the rows that satisfy the following conditions,
     * ByUsername --> username is a field in entity class,
     * @param pageable: pagination is applied on the data.
     * @return 
     */
    public Page<Entity> findAllByUsername(String username, Pageable pageable);

}

, :

public Page<EntityDTO> findByUsername(String username, Pageable pageable){
    Page<Entity> entityPage = entityRepository.findAllByUsername(username, pageable);
    List<EntityDTO> dtos = mapper.entityToEntityDTOs(entityPage.getContent());
    return new PageImpl<>(dtos, pageable, entityPage.getTotalElements());
}

Mapstruct mapper:

import org.mapstruct.factory.Mappers;

/**
 * Mapper for converting entity to DTO.
 */
@Mapper(componentModel = "spring", uses = {})
public interface Mapper {

    /**
     * The interface declares a member INSTANCE, providing clients access to the mapper implementation,
     * which is the file target\generated-sources\com\company\springapp\dto\mappers\MapperImpl.java
     * (automatically generated when compiling the project).
     */
    AuditMapper INSTANCE = Mappers.getMapper( Mapper.class );

    /**
     * Convert entity to DTO.
     * Mappings are used to 'bind' entity fields to DTO fields (for the mapper implementation).
     * @param entity
     * @return 
     */
    @Mappings({
        @Mapping(source = "id", target = "id"),
        @Mapping(source = "username", target = "dtoUsername"),
        @Mapping(source = "action", target = "dtoAction")
    })
    public EntityDTO entityToEntityDTO(Entity entity);

    /**
     * Convert entities' list to DTOs' list.
     * @param entities
     * @return 
     */
    public List<EntityDTO> entitiesToEntityDTOs(List<Entity> entities);

}
+2

All Articles