1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Spring Data JPAのクエリメソッドまとめ

1
Posted at

クエリメソッドとは

Spring Data JPAでは、Repositoryに定義したメソッド名からクエリを自動生成できます。

Optional<User> findByEmail(String email);

例えば上記の場合、

select *
from users
where email = ?

相当のクエリが自動生成されます。

基本構造

戻り値 + メソッド名(引数)

Optional<Coupon> findById(Long id)
List<Coupon> findAllByUserId(String userId)
Page<Coupon> findAllByUserId(String userId, Pageable pageable)

先頭のキーワードによる違い

メソッド例 意味
findBy 条件を指定して取得
existsBy 条件に一致するデータの存在確認
countBy 条件に一致する件数取得
deleteBy 条件に一致するデータの削除
removeBy 条件に一致するデータの削除(deleteByと同義)

戻り値による違い

戻り値 意味
Entity 1件返す
Optional 0件 or 1件返す
List 0件以上の複数件を返す
Set 0件以上の複数件を返す
Collection 0件以上の複数件を返す
Iterable 0件以上の複数件を返す
Page ページング結果を返す
Slice 次ページがあるかだけ分かる一覧
Stream 大量データを流しながら処理
boolean / Boolean 存在確認結果を返す
long / Long 件数を返す(countBy や deleteBy)
int / Integer 更新・削除件数を返す
void 戻り値なし

使用例

メソッド例 意味
Optional findById(Long id) IDで0件または1件取得
List findAllByUserId(String userId) userIdに紐づく一覧取得
Page findAllByUserId(String userId, Pageable pageable) ページング取得
boolean existsByUserId(String userId) 存在確認
long countByUserId(String userId) 件数取得
void deleteByUserId(String userId) 削除

まとめ

Spring Data JPAでは、Repositoryのメソッド名からクエリを自動生成できます。
findBy・existsBy・countBy・deleteBy などの命名規則を利用することで、簡単な検索や存在確認であればSQLを書かずに実装できます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?