Spring Boot Data JPA でSortしたデータを取得する方法

Spring Boot Data JPA でSortしたデータを取得する方法をご紹介します。

まずはデータ部分に相当する @Entityクラスを作ります。Lombokを使用しているので、@Dataをクラスに付与してSetter/Getterを自動生成しています。

@Data
@Entity
public class TestInfo {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Integer id;
  private Date updateTime;
}

そして、データ部分を扱うRepositoryを作ります。今回は「ソートして取得」の定義を作ります。

import org.springframework.data.domain.Sort;
...

@Repository
public interface TestInfoRepository extends JpaRepository<TestInfo, Integer> {
  List<TestInfo> findByid(Integer id, Sort sort);
}

Controller 部に先ほど定義したRepositoryを使ってデータを取得するように書きます。

import org.springframework.data.domain.Sort;
...

@Controller
public class SampleController {

  @Autowired
  TestRepository testRepository;
  @RequestMapping(value = "/", method = RequestMethod.GET)
  public void index() {

  //     Sort sort = new Sort(Direction.ASC, "testStatus").and(new Sort(Direction.DESC, "updateTime"));
  Sort sort = new Sort(Direction.DESC, "updateTime");

  List<TestInfo> testInfoList = testRepository.findByid(id, sort);
  
  }
}

これで完成です。Sortしたデータを取得することが出来ます。