0
1

Spring Data JPA(Java Persistence API)のクエリメソッドの種類一覧

Posted at

■ 概要

Spring Data JPAの機能であるクエリメソッドで使いそうなメソッドをまとめた

■ 基本的なクエリメソッド

● 全てのエンティティ

List<Item> items = itemRepository.findAll();
生成されるクエリ
SELECT i FROM Item i

● 指定されたIDに対応するエンティティ

Optional<Item> item = itemRepository.findById(1);
生成されるクエリ
SELECT i FROM Item i WHERE i.id = :id

● 指定されたIDのエンティティが存在するかを確認

boolean exists = itemRepository.existsById(1);
生成されるクエリ
SELECT COUNT(i) > 0 FROM Item i WHERE i.id = :id

● 単一のエンティティを保存または更新

Item savedItem = itemRepository.save(item);
生成されるクエリ
-- 挿入の場合
INSERT INTO Item (fields...) VALUES (values...)
-- 更新の場合
UPDATE Item SET field1 = value1, field2 = value2, ... WHERE id = :id

● 複数のエンティティを保存または更新

List<Item> items = Arrays.asList(item1, item2);
List<Item> savedItems = itemRepository.saveAll(items);
生成されるクエリ
INSERT INTO Item (fields...) VALUES (values...)
UPDATE Item SET field1 = value1, field2 = value2, ... WHERE id = :id

● 指定されたIDのエンティティを削除

itemRepository.deleteById(1);
生成されるクエリ
DELETE FROM Item i WHERE i.id = :id

● 全てのエンティティを削除

itemRepository.deleteAll();
生成されるクエリ
DELETE FROM Item

● エンティティの総数を返します。

long count = itemRepository.count();
生成されるクエリ
SELECT COUNT(i) FROM Item i

■ リポジトリで定義できる単純なクエリメソッド

● 並び替え

OrderBy : 指定されたプロパティでソートすることを指定
Asc, Desc : 昇順、降順でソートすることを指定

public interface ItemsRepository extends JpaRepository<ItemsEntity, Integer> {
    // 昇順
    List<Item> findAllByOrderByPriceASC();
    // 降順
    List<Item> findAllByOrderByPriceDesc();
}
生成されるクエリ
SELECT i FROM Item i ORDER BY i.price ASC
SELECT i FROM Item i ORDER BY i.price DESC

● 条件検索

public interface ItemsRepository extends JpaRepository<ItemsEntity, Integer> {
    List<Item> findByPrice(Integer keyword);
}
生成されるクエリ
SELECT i FROM Item i WHERE i.keyword = :keyword

● 条件検索 複数の場合

And : 複数の条件を組み合わせることを示す

public interface ItemsRepository extends JpaRepository<Item, Integer> {
    List<Item> findByNameAndPrice(String keyword1, Integer keyword2);
}
生成されるクエリ
SELECT i FROM Item i WHERE i.keyword1 = :keyword1 AND i.keyword2 = :keyword2

● 曖昧検索

Containing : 部分一致検索を行うことを示す

public interface ItemsRepository extends JpaRepository<Item, Integer> {
    List<Item> findByNameContaining(String keyword);
}
生成されるクエリ
SELECT i FROM Item i WHERE i.name LIKE %:keyword%
0
1
0

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
0
1