0
Help us understand the problem. What are the problem?

posted at

【Java】SpringBootでPaging&Sortしてみた。

参考

pom.xml

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

Repository

@Repository
public interface SampleUserRepository
    extends CrudRepository<SampleUserEntity, Integer>, JpaSpecificationExecutor<SampleUserEntity> {
}

Service

  public SampleUserSearchResponse search(SampleUserSearchRequest request) {
    Specification<SampleUserEntity> specs = // generate specifications in some way
    PageRequest pageRequest = PageRequest.of(request.getPage(), request.getSize(),
        sortBuild(request.getSortKey(), request.isDesc()));

    Page<SampleUserEntity> sampleUsers = sampleUserRepository.findAll(specs, pageRequest);

    int totalPage = (int) Math.ceil((double) sampleUsers.getTotalElements() / request.getSize());

    return new SampleUserSearchResponse(totalPage,
        modelMapper.map(sampleUsers.getContent(), new TypeToken<List<SampleUserDto>>() {
        }.getType()));
  }

Request

public class SampleUserSearchRequest {
  private String name;
  private Integer age;
  private String sortKey;
  private boolean isDesc;
  private int size;
  private int page;
}

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
0
Help us understand the problem. What are the problem?