spring-data-jpa 将页面转换< Entity>为PageDTO< EntityDTO>

uemypmqf  于 2022-11-10  发布在  Spring
关注(0)|答案(2)|浏览(253)

我使用的是Spring Data JPA。
我的控制器看起来如下

@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);
    }

现在我决定发送一个PageDTO对象而不是Page对象来限制发送。有没有什么方法可以用java 8将Page转换为PageDTO?
我看到Page是从Iterable派生的,所以我想我可以做一些类似以下的事情,但不知道如何将它与PageDTO和UserDTO放在一起。

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

有没有什么有效Java8方法可以做到这一点?
我想出了这个办法

@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());
    }

想知道是否有其他有效的方法来做到这一点?

zujrkrfu

zujrkrfu1#

我知道这是一个老问题,但我遇到了同样的问题,我想提供一个可能的解决方案给任何可能感兴趣的人。下面是我发现的帮助我编写代码的东西: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);

}

这是我进行Map的方法:

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());
}

我的MapstructMap器:

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's 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);

}
63lcw9qa

63lcw9qa2#

这个答案太晚了,但这个解决方案对我很有效
服务

public Page<EntityDto> getAllEntities(Pageable pageable) {
    return entityRepository.findAll(pageable).map(entityMapper::toEntityDto);
}

Map器

import org.mapstruct.Mapper;

@Mapper(componentModel = "spring")
public interface EntityMapper {
    EntityDto toEntityDto(Entity entity);
}

控制器

@GetMapping(path = "/entities")
    public List<EntityDto> getAllEntities(Pageable pageable) {
        Page<EntityDto> page = entityService.getAllEntities(pageable);
        return page.getContent();
    }

这将从第一页返回size = 10的实体列表

http://localhost:port/api/entities?page=0&size=10

感谢JHipster!

相关问题