1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MyBatis 自動生成ファイルの使い方

1
Last updated at Posted at 2025-08-31

業務でMyBatis Generatorを使う機会があり、基本的な使い方を整理したので共有します。

MyBatis Generator によって自動生成されるファイルを使えば、XMLファイルを手書きする必要がなくなり、以下のような基本的な SQL 操作に対応できます。
今回は SELECT / INSERT / UPDATE に絞って紹介します。

🔍 SELECT

JOIN を必要としない単一テーブルからの SELECT であれば、自動生成ファイルのみで十分対応可能です。
自動生成されるファイルは以下の2種類で、テーブルごとに作成されます:

  • Book.java
  • BookExample.java

全件取得するサンプル:

public List<Book> findAll() {
    // 条件なしで全件取得
    return BookMapper.selectByExample(new BookExample());
}

削除されていないレコードのみ取得するサンプル:
論理削除フラグ deleted が false のレコードのみ取得する例。

public List<Book> findAll() {
    BookExample example = new BookExample();
    example.createCriteria().andDeletedEqualTo(false);
    return BookMapper.selectByExample(example);
}

<補足>

  • BookExampleは検索条件を組み立てるためのクラスで、内部にCriteriaを持ち、AND条件などをメソッドチェーンで記述できます。

INSERT

insertSelectiveメソッドを使うことで、Entityクラスに値が格納された非nullフィールドのみ対象としてINSERTされます。

public void insert(Book book) {
    book.setBookName("システム設計の基本");
    bookMapper.insertSelective(book);
}

UPDATE

Service
updateByPrimaryKeySelectiveメソッドを使うことで、エンティティに格納されたプライマリキーに対応するレコードの、非nullフィールドを対象としてUPDATEされます。

public void update(Book book) {
    book.setBookName("MyBatis入門");
    bookMapper.updateByPrimaryKeySelective(book);
}

<補足>
※プライマリキー以外の条件を使った更新も可能です。こちらは後ほど追記予定です。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?