LoginSignup
13
7

More than 1 year has passed since last update.

Spring Data JPAのソート

Last updated at Posted at 2020-12-30

findAll()メソッドでのソートに苦労したので備忘録を残しておきます。

単一条件でのソート方法

クエリメソッド

クエリメソッドで実装する方法。
JPAにはRepositoryインターフェースに、命名規則に従ったメソッド名を書くとSQLを自動生成する機能があります。
この方法で実装するのが一般的なようです。

Repositoryクラス
@Repository
public interface xxxRepository extends JpaRepository<xxxEntity, Integer>    
    public List<xxxEntity> findAllByOrderByBigId();
}

サービスクラスで実装

サービスクラスでソートを実装する場合は下記のようになります。

Repositoryクラス
@Repository
public interface xxxRepository extends JpaRepository<xxxEntity, Integer> {
    public List<xxxEntity> findAll();
}
Serviceクラス
    @Autowired
    private xxxRepository repository;

    public List<xxxEntity> accountFindAll(){

        return repository.findAll(
                Sort.by(Sort.Direction.ASC, "bigId")
    }

PageRequest.ofでソート

public static PageRequest of(int page, int size, Sort sort)

Serviceクラス
Pageable pageable =
  PageRequest.of(0, 3, Sort.by("bigId"));

複数条件でのソート方法

クエリメソッドで実装

Repositoryクラス
@Repository
public interface xxxRepository extends JpaRepository<xxxEntity, Integer> {
    public List<xxxEntity> findAllByOrderByBigIdNormalIdSmallId();
}

@Queryで実装

クエリメソッドでは、メソッド名が長くなりすぎてしまう場合は@Queryでの実装も検討します。

Repositoryクラス
@Repository
public interface xxxRepository extends JpaRepository<xxxEntity, Integer> {
    @Query(value = "SELECT xxxEntity s FROM s order by s.bigId, s.normalId, s.smallId")
    public List<xxxEntity> findAllOrderByAllId();
}

サービスクラスで実装

Repositoryクラス
@Repository
public interface xxxRepository extends JpaRepository<xxxEntity, Integer> {
    public List<xxxEntity> findAll();
}
Serviceクラス
    @Autowired
    private xxxRepository repository;

    public List<xxxEntity> accountFindAll(){

        return repository.findAll(
                Sort.by(Sort.Direction.ASC, "bigId")
                .and(Sort.by(Sort.Direction.ASC, "normalId"))
                .and(Sort.by(Sort.Direction.ASC, "smallId")));
    }

PageRequest.ofでソート

Serviceクラス
Pageable pageable =
  PageRequest.of(0, 5, Sort.by("bigId").descending().and(Sort.by("normalId")).and(Sort.by("smallId"));

参考サイト

Spring Data JPA でのクエリー実装方法まとめ
SpringBoot JPA Sort 書き方が変わった?
Spring Data JPAを使用したページ区切りとソート

環境

Java:11
SpringBoot:2.3.1

13
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
7