はじめに
MyBatis Generatorには公式のMavenプラグインが用意されていますが、Gradleプロジェクトで使用する場合はサードパーティ製のプラグインに依存するか、JARを直接実行する必要があります。
外部プラグインへの依存を避けてプロジェクト管理をシンプルにしたい場合は、自作のGradleタスクとして組み込む方法が有効です。
本記事では、外部プラグインに頼らず、MyBatis Generatorの自動生成をGradleタスクとして実装する方法を解説します。
GradleはAntタスクを直接実行できるため、MyBatis Generatorから提供されているAnt用自動生成タスククラスを利用することで、簡単にGradleタスクとして実装できます。
この手法を用いることで、Spring Boot × MyBatis × Gradleプロジェクトにおいて、データベーススキーマの変更に迅速に対応できるほか、ボイラープレートコードの自動生成によって手作業によるミスを減らすことができます。
対象読者
- MyBatis × Gradleを使用したプロジェクトに従事している方
- データベーススキーマからのコード自動生成を効率化したい方
- Spring BootプロジェクトでMyBatis Generatorの運用を検討している方
環境
| 項目 | バージョン |
|---|---|
| Java | 21 |
| Gradle | 9.2.1 |
| MyBatis Generator | 1.4.2 |
| H2 | 2.4.240(動作確認用) |
| Spring Boot | 4.0.0(動作確認用) |
本記事ではデータベースにH2を利用していますが、MyBatis GeneratorはJDBCドライバーが用意されている一般的なデータベースに対応しています。プロジェクトに合わせて適宜読み替えてください。
MyBatis Generatorとは
MyBatis GeneratorはMyBatisが提供する公式のコード生成ツールです。データベーススキーマを元に以下のファイルを自動生成できます。
- エンティティクラス
- Mapperインターフェース
- Mapper XMLファイル
これらのコードを自動生成することで、データベーススキーマの変更に伴う手作業でのコード修正によるバグの発生を抑えることができます。
プロジェクト構成
以下のようなプロジェクト構成を想定しています。
.
│ build.gradle // 1
│ gradlew
│ gradlew.bat
├───.gradle
├───gradle
└───src
└───main
├───java
│ └───com
│ └───example
│ │ ExampleApplication.java // 2
│ │ ExampleController.java // 3
│ │
│ ├───entity // 4
│ └───mapper // 5
│
└───resources
│ application.properties
│ data.sql
│ schema.sql
│
└───com
└───example
└───mapper // 6
- Gradleのビルド設定ファイル
- 動作確認用のアプリケーションクラス
- 動作確認用のコントローラークラス
- 自動生成されるエンティティクラスの配置場所
- 自動生成されるMapperインターフェースの配置場所
- 自動生成されるMapper XMLファイルの配置場所
実装手順
1. データベースの準備
本記事では、以下のようなテーブル構造のデータベースを用意します。
CREATE TABLE example_table
(
id INT NOT NULL PRIMARY KEY,
name VARCHAR(32) NOT NULL,
description TEXT,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
動作確認用に以下のダミーデータが挿入されているものとします。
INSERT INTO example_table (id, name, description, created_at, updated_at) VALUES
(1, 'Example1', 'This is the first example data', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
(2, 'Example2', 'This is the second example data', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);
2. build.gradleの設定
GradleはAntタスクを直接実行できるため、MyBatis Generatorが提供しているAnt用の自動生成タスククラスを利用することが可能です。
https://mybatis.org/generator/running/runningWithAnt.html
そのため、build.gradleにMyBatis Generatorの自動生成タスククラスに必要な依存関係を追加することで、Gradleから自動生成処理を実行できます。
plugins {
id 'java'
id 'org.springframework.boot' version '4.0.0'
id 'io.spring.dependency-management' version '1.1.7'
}
group = 'com.example'
version = '1.0.0'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
repositories {
mavenCentral()
}
configurations {
// MyBatis Generatorによる自動生成タスク用の依存関係のスコープを宣言します
mybatisTasks
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:4.0.0'
implementation 'com.h2database:h2'
// MyBatis GeneratorとJDBCドライバの依存関係を追加します
mybatisTasks 'org.mybatis.generator:mybatis-generator-core:1.4.2'
mybatisTasks 'com.h2database:h2'
}
tasks.register('runMyBatisGenerator') {
doLast {
// Antタスクを定義します
ant.taskdef(
name: 'mybatisGenerator',
// MyBatis Generatorが提供する自動生成のAntタスククラスを指定します
classname: 'org.mybatis.generator.ant.GeneratorAntTask',
// MyBatis GeneratorのAntタスク実行時に使用するクラスパスを指定します
classpath: configurations.mybatisTasks.asPath
)
// 上記に定義したAntタスクを実行します
ant.mybatisGenerator(
// 生成するファイルの上書きを許可します
overwrite: true,
// MyBatis Generatorの設定ファイルを指定します
configfile: file('src/main/resources/generatorConfig.xml'),
// 詳細なログを出力します
verbose: true
)
}
}
3. generatorConfig.xmlの作成
MyBatis Generatorの設定を行うgeneratorConfig.xmlを作成します。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
<context id="local" targetRuntime="MyBatis3">
<!-- 生成するMapperに@Mapperアノテーションを付与するプラグイン -->
<plugin type="org.mybatis.generator.plugins.MapperAnnotationPlugin"/>
<!-- 接続先DB情報 -->
<jdbcConnection driverClass="org.h2.Driver"
connectionURL="jdbc:h2:file:~/data;"
userId=""
password="" />
<!-- Model(Entity)作成先 -->
<javaModelGenerator targetPackage="com.example.entity"
targetProject="/dev/example/src/main/java" />
<!-- Mapper.xml作成先 -->
<sqlMapGenerator targetPackage="com.example.mapper"
targetProject="/dev/example/src/main/resources" />
<!-- Mapper.java作成先 -->
<javaClientGenerator targetPackage="com.example.mapper"
targetProject="/dev/example/src/main/java"
type="XMLMAPPER" />
<!-- 生成対象テーブル -->
<table schema="" tableName="EXAMPLE_TABLE" domainObjectName="ExampleEntity" mapperName="ExampleMapper">
<!-- 主キーをDB側で自動採番する場合の設定 -->
<generatedKey column="id" sqlStatement="H2" identity="true"/>
</table>
</context>
</generatorConfiguration>
MyBatis Generatorによる自動生成コードはプラグインを使用することで、カスタマイズすることができます。
本記事では、Mapperインターフェースに@Mapperアノテーションを付与するプラグインを使用しています。
その他のプラグインは以下を参照してください。
https://mybatis.org/generator/reference/plugins.html
4. タスクの実行
以下のコマンドでMyBatis Generatorを実行します。
./gradlew runMyBatisGenerator
実行後、以下のファイルが自動生成されます。
src/main/java/com/example/entity/ExampleEntity.javasrc/main/java/com/example/entity/ExampleEntityExample.javasrc/main/java/com/example/mapper/ExampleMapper.javasrc/main/resources/com/example/mapper/ExampleMapper.xml
5. 自動生成されたコードの利用例
application.propertiesに接続先DB情報を追記します。
spring.datasource.url=jdbc:h2:file:~/data;
spring.datasource.username=
spring.datasource.password=
アプリケーションクラスの@SpringBootApplicationにコンポーネントスキャンの設定を追記します。
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = "com.example")
public class ExampleApplication {
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
}
コントローラークラスのメソッドで、生成されたMapperを用いてデータベースに登録されたデータを取得します。
package com.example;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.example.entity.ExampleEntity;
import com.example.mapper.ExampleMapper;
@RestController
public class ExampleController {
private final ExampleMapper exampleMapper;
public ExampleController(ExampleMapper exampleMapper) {
this.exampleMapper = exampleMapper;
}
@GetMapping("{id}")
public ResponseEntity<ExampleEntity> hello(@PathVariable Integer id) {
ExampleEntity entity = exampleMapper.selectByPrimaryKey(id);
return ResponseEntity.ok(entity);
}
}
./gradlew bootRunなどでアプリを起動し、http://localhost:ポート番号/1にアクセスして、以下のようなJSONが返却されれば成功です。
{
"id": 1,
"name": "Example1",
"description": "This is the first example data",
"createdAt": "20xx-xx-xxT12:xx:xxZ",
"updatedAt": "20xx-xx-xxT12:xx:xxZ"
}
まとめ
本記事では、サードパーティ製プラグインに依存せず、MyBatis Generatorの自動生成をGradleタスクとして実装する方法を解説しました。
GradleからMyBatis Generatorを実行することで、以下のメリットがあります。
- データベーススキーマの変更に迅速に対応できる
- 手作業によるコーディングミスを削減できる
- 開発効率が大幅に向上する
- チーム全体で統一されたコード生成ルールを適用できる
本記事の設定を参考に、プロジェクトに合わせてカスタマイズしてご利用ください。
参考リンク
We Are Hiring!