MyBatis Generatorを使ってDBテーブルからJavaモデルとMapperを自動生成する

概要

手作業でエンティティクラスやXMLマッパーを書くのは時間がかかりがちです。MyBatis Generator(MBG)を利用すれば、既存のデータベーススキーマを読み取り、POJO・Mapperインターフェース・SQL XMLを一括で作成できます。以降ではMavenベースのプロジェクトでMySQLテーブルt_userを題材に、MBGを実行する手順を紹介します。

1. Maven依存とプラグイン設定

pom.xmlにMyBatis Generator本体とMySQLドライバを追加し、プラグイン側でもドライバを再宣言しておくことで、mvn mybatis-generator:generateを叩くだけでコード生成が可能になります。

<project>
  ...
  <properties>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>com.mysql</groupId>
      <artifactId>mysql-connector-j</artifactId>
      <version>8.3.0</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis.generator</groupId>
      <artifactId>mybatis-generator-core</artifactId>
      <version>1.4.2</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.4.2</version>
        <configuration>
          <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
          <overwrite>true</overwrite>
        </configuration>
        <dependencies>
          <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>8.3.0</version>
          </dependency>
        </dependencies>
      </plugin>
    </plugins>
  </build>
</project>

2. サンプルテーブル作成

MySQLにdemoデータベースを作成し、次のDDLでt_userを用意します。

CREATE TABLE t_user (
  user_id   INT AUTO_INCREMENT PRIMARY KEY,
  user_name VARCHAR(50) NOT NULL,
  user_age  TINYINT     NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

3. generatorConfig.xml

MBGの設定ファイルをsrc/main/resources/generatorConfig.xmlに配置します。コメントを省いた最小構成は以下の通りです。

<?xml version="1.0" encoding="UTF-8"?>
<generatorConfiguration>
  <context id="mysqlContext"
           defaultModelType="flat"
           targetRuntime="MyBatis3">

    <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                    connectionURL="jdbc:mysql://localhost:3306/demo?serverTimezone=UTC"
                    userId="root"
                    password="root"/>

    <javaModelGenerator targetPackage="com.example.demo.domain"
                        targetProject="src/main/java">
      <property name="enableSubPackages" value="true"/>
      <property name="trimStrings" value="true"/>
    </javaModelGenerator>

    <sqlMapGenerator targetPackage="mapper"
                     targetProject="src/main/resources">
      <property name="enableSubPackages" value="true"/>
    </sqlMapGenerator>

    <javaClientGenerator type="XMLMAPPER"
                         targetPackage="com.example.demo.mapper"
                         targetProject="src/main/java">
      <property name="enableSubPackages" value="true"/>
    </javaClientGenerator>

    <table tableName="t_user"
             domainObjectName="User"
             enableCountByExample="false"
             enableUpdateByExample="false"
             enableDeleteByExample="false"
             enableSelectByExample="false"
             selectByExampleQueryId="false">
      <generatedKey column="user_id" sqlStatement="MySql"/>
    </table>
  </context>
</generatorConfiguration>

4. コード生成実行

プロジェクトルートで次のコマンドを実行します。

mvn mybatis-generator:generate

成功すると、次のようなログが出力され、src/main/java/com/example/demo/domain/User.javaUserMapper.javasrc/main/resources/mapper/UserMapper.xmlが自動生成されます。

[INFO] --- mybatis-generator-maven-plugin:1.4.2:generate (default-cli) @ demo ---
[INFO] Connecting to the Database
[INFO] Introspecting table t_user
[INFO] Generating Record class for table t_user
[INFO] Generating Mapper Interface for table t_user
[INFO] Generating SQL Map XML for table t_user
[INFO] Saving file UserMapper.xml
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS

これでMyBatis Generatorを使った自動生成のセットアップは完了です。テーブル定義を変更した場合は再実行するだけで最新のコードが得られるため、開発効率が大幅に向上します。

タグ: MyBatis Generator MyBatis Maven MySQL Java

6月17日 23:57 投稿