我使用的是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());
}
想知道是否有其他有效的方法来做到这一点?
2条答案
按热度按时间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页面将具有相同的参数(页码、大小等)。
这是我进行Map的方法:
我的MapstructMap器:
63lcw9qa2#
这个答案太晚了,但这个解决方案对我很有效
服务
Map器
控制器
这将从第一页返回size = 10的实体列表
感谢JHipster!