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

【SpringBoot】Repositoryとは

0
Last updated at Posted at 2025-11-12

Repositoryとは

Springアプリは、下のような「3層構造」で作られています。
この中でデータベースへ保存・検索・削除などを行う部分を指します。

役割
Controller 画面やAPIからのリクエストを受け取る
Service ビジネスロジックを処理する
Repository データベースへ保存・検索・削除などを行う

Repositoryの実装

Repositoryの実装には、以下の要素が必要になる。
1.「JpaRepositoryを継承したインターフェース
2.「任意のクエリメソッド

実装例:

.java
package com.example.demo.repository;

import com.example.demo.domain.Book;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;

// 1. JpaRepositoryを継承したインターフェース
public interface BookRepository extends JpaRepository<Book, Long> {
    // 2. 任意のクエリメソッド
    Page<Book> findByTitleContainingIgnoreCase(String keyword, Pageable pageable);
}


1. JpaRepositoryを継承したインターフェース

//                リポジトリ名                    テーブル名,主キーの型 
public interface BookRepository extends JpaRepository<Book, Long>

JpaRepository は、
Spring Data JPA が提供する CRUDを自動化するインターフェースです。

C:Create(作成)データの登録
R:Read(読み取り)データの取得
U:Update(更新)データの変更
D:Delete(削除)データの削除

継承することで、DB操作をSQL文を書かないで実行できる仕組みが提供されます:
(実装クラスは自動生成される)

関数名 DB操作 例:自動生成されるSQL文
findAll() 全件取得 SELECT * FROM book;
findById(Long id) 主キーで1件取得 SELECT * FROM book WHERE id = ?;
save(Book book) 新規登録 or 更新 INSERT または UPDATE
deleteById(Long id) IDで削除 DELETE FROM book WHERE id = ?;
count() 件数取得 SELECT COUNT(*) FROM book;
existsById(Long id) 存在確認 SELECT COUNT(*) ... > 0

2. 任意のクエリメソッド

.java
// 例:タイトルに指定文字列を含む Book を(大文字小文字の区別なく)検索し、ページングして返す
Page<Book> findByTitleContainingIgnoreCase(String keyword, Pageable pageable);

Spring Data JPA では、SQL文を書かなくても
メソッド名のルールに従うだけで自動的に検索処理を作ることができます。

「findBy + フィールド名 + 条件キーワード」のように記述します。。

List<Book> findByAuthor(String author);

この1行だけで、以下のSQLと同じ処理を自動的に実行できます。

SELECT * FROM book WHERE author = ?;

例:AND 条件

List<Book> findByAuthorAndPriceGreaterThan(String author, Integer price);

author が一致 かつ price が指定値より大きい

SELECT * FROM book WHERE author = ? AND price > ?;

例:OR 条件

List<Book> findByTitleContainingOrAuthorContaining(String title, String author);

title または author にキーワードが含まれる

SELECT * FROM book WHERE title LIKE ? OR author LIKE ?;

例:ページング・ソート

クエリメソッドの引数に Pageable を追加すると、
ページングソート に対応した検索ができる。

Page<Book> findByTitleContainingIgnoreCase(String keyword, Pageable pageable);

呼び出し例:

Pageable pageable = PageRequest.of(0, 10, Sort.by("createdAt").descending());
Page<Book> page = bookRepository.findByTitleContainingIgnoreCase("java", pageable);

Page<Book>
Spring Data JPA における ページングの検索結果 を表すクラス。
ページングに必要な情報が格納される。
getContent()→実際の Book データ(List 型)
getTotalElements()→全体の件数
getTotalPages()→全ページ数
getNumber()→現在のページ番号
getSize()→1ページあたりの件数
isFirst() / isLast()→最初・最後のページかどうか
hasNext() / hasPrevious()→次・前のページがあるかどうか


条件キーワード一覧

キーワード 条件
Is / Equals 一致 findByAuthor(=findByAuthorIs
Not 否定 findByAuthorNot(String name)
Like 部分一致 findByTitleLike("%Java%")
Containing 含む(LIKE %値% findByTitleContaining("Java")
StartingWith 前方一致(LIKE 値% findByTitleStartingWith("Spring")
EndingWith 後方一致(LIKE %値 findByTitleEndingWith("Guide")
IgnoreCase 大文字小文字を区別しない findByTitleIgnoreCase("spring")
GreaterThan より大きい(>) findByPriceGreaterThan(1000)
LessThan より小さい(<) findByPriceLessThan(500)
Between 範囲(BETWEEN) findByPriceBetween(1000, 3000)
In 複数値を指定 findByAuthorIn(List<String> authors)
OrderBy 並び順指定 findByAuthorOrderByPriceDesc()
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?