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

【Java】MariaDB(MySQL)とStruts2(ver6系)でMyBatisGeneratorを使ってEntityとMapperとXML を自動生成する

Last updated at Posted at 2026-01-03

image.png

今回は、Struts2(ver6系)にMyBatisを導入して、テーブルからEntityやMapperを自動生成する方法を紹介します。

ER図作成のためのおすすめツール

MyBatisは、テーブル情報からEntityやMapperクラスを自動生成するツールなので、下記の手順に沿って進めていきます。
【手順】
■テーブルの生成:DDLファイルでテーブルを生成
mybatis-config.xmlの作成と更新
generatorConfig.xmlの作成と更新
■Mavenライブラリとプラグインをpom.xmlに導入
mvn mybatis-generator:generateコマンドでEntityやMapperクラスを自動生成

テーブルの生成

今回は、管理者テーブル(adminusers)と管理者プロフィールテーブル(admin_photo)のDDLを作成します。

image.png

image.png

CreateAdminUsers.sql
CREATE TABLE adminusers (
  id VARCHAR(50) NOT NULL,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(255) NOT NULL,
  password VARCHAR(255) NOT NULL,
  gender CHAR(1) NOT NULL COMMENT 'M:男性 F:女性 O:その他',
  office VARCHAR(20) NOT NULL,
  admin_role TINYINT(1) NOT NULL DEFAULT 0,
  PRIMARY KEY (id),
  UNIQUE KEY uk_adminusers_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CreateAdminUsersProfile.sql
CREATE TABLE adminuser_photos (
  id INT AUTO_INCREMENT PRIMARY KEY,
  adminuser_id VARCHAR(50) NOT NULL,
  file_path VARCHAR(255) NOT NULL,
  sort_order INT NOT NULL,
  FOREIGN KEY (adminuser_id) REFERENCES adminusers(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

管理者プロフィールテーブル(admin_photo)として分けたのは拡張性に欠けていたからです。
profileFiles VARCHAR(100)
"a.jpg,b.jpg,c.jpg"
のように詰める方法は 非推奨 です。

理由:
■検索・更新が面倒
■将来「4枚にしたい」時に壊れる
■正規化違反

mybatis-config.xmlの作成と更新

src/main/resources配下にmybatis-config.xmlを新規作成し、下記のように更新します。

mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

  <!-- DB接続設定 -->
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url"
          value="jdbc:mysql://localhost:3306/strutsDB?useSSL=false&amp;serverTimezone=Asia/Tokyo"/>
        <property name="username" value="root"/>
        <property name="password" value="password"/>
      </dataSource>
    </environment>
  </environments>

  <!-- Mapper登録 -->
  <mappers>
    <mapper resource="mapper/AdminUserMapper.xml"/>
  </mappers>

</configuration>

generatorConfig.xmlの作成と更新

src/main/resources配下にgeneratorConfig.xmlを新規作成し、下記のように更新します。
配置場所👇

src/main/resources/generatorConfig.xml
generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "https://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>

  <!-- ★ context が必須 -->
  <context id="MySQLTables" targetRuntime="MyBatis3">

    <!-- コメント抑制(任意) -->
    <commentGenerator>
      <property name="suppressAllComments" value="true"/>
    </commentGenerator>

    <!-- JDBC接続設定 -->
    <jdbcConnection
        driverClass="com.mysql.cj.jdbc.Driver"
        connectionURL="jdbc:mysql://localhost:3306/strutsDB?useSSL=false&amp;serverTimezone=Asia/Tokyo"
        userId="root"
        password="<パスワード>"/>

    <!-- Entity -->
    <javaModelGenerator
        targetPackage="model"
        targetProject="src/main/java">
      <property name="trimStrings" value="true"/>
    </javaModelGenerator>

    <!-- Mapper XML -->
    <sqlMapGenerator
        targetPackage="mapper"
        targetProject="src/main/resources"/>

    <!-- Mapper Interface -->
    <javaClientGenerator
        type="XMLMAPPER"
        targetPackage="mapper"
        targetProject="src/main/java"/>

    <!-- adminusers -->
    <table tableName="adminusers"
           domainObjectName="AdminUser"/>

    <!-- adminuser_photos -->
    <table tableName="adminuser_photos"
           domainObjectName="AdminUserPhoto">
      <generatedKey column="id" sqlStatement="JDBC"/>
    </table>

  </context>
</generatorConfiguration>

pom.xmlにMavenライブラリとプラグインの導入

pom.xmlに下記のライブラリを導入していきます。

MySQL Connectorライブラリの導入

MySQLドライバをインストールします。
image.png
👇下記をpom.xmlへコピー&ペーストしてください。👇

pom.xml
<!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>9.5.0</version>
</dependency>

MyBatisライブラリの導入

ORマッパーの1つであるMyBatisをインストールします。
image.png

👇下記をpom.xmlへコピー&ペーストしてください。👇

pom.xml
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.19</version>
</dependency>

MyBatisGenerator Coreライブラリの導入

データベーステーブルからEntityを自動生成するライブラリMyBatisGenerator Coreを導入します。
image.png

👇下記をpom.xmlへコピー&ペーストしてください。👇

pom.xml
<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.4.2</version>
</dependency>

途中までまとめると下記のようになります。
image.png

mybatis-generator-maven-pluginプラグインの導入

MyBatisGenetratorを起動させるためのプラグインmybatis-generator-maven-pluginも導入します。
👇下記をpom.xmlへコピー&ペーストしてください。👇

pom.xml
<!--MyBatis追加-->
<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.4.1</version>
    <configuration>
        <configurationFile>${project.basedir}/src/main/resources/generatorConfig.xml</configurationFile>
        <overwrite>true</overwrite>
        <includeAllDependencies>true</includeAllDependencies>
    </configuration>
</plugin>

下記のように導入できればOKです。
image.png

全体のpom.xmlは下記となります。

pom.xml
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>StrutsApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>StrutsApp</name>
    <description>Struts 2 Starter</description>

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

        <struts2.version>6.1.1</struts2.version>
        <log4j2.version>2.19.0</log4j2.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>${struts2.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-sitemesh-plugin</artifactId>
            <version>${struts2.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-spring-plugin</artifactId>
            <version>${struts2.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-config-browser-plugin</artifactId>
            <version>${struts2.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${log4j2.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${log4j2.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>org.directwebremoting</groupId>
            <artifactId>dwr</artifactId>
            <version>3.0.2-RELEASE</version>
        </dependency>

        <!-- Tests -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
		<!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
		<dependency>
		    <groupId>com.mysql</groupId>
		    <artifactId>mysql-connector-j</artifactId>
		    <version>9.5.0</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis</artifactId>
		    <version>3.5.19</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
		<dependency>
		    <groupId>org.mybatis.generator</groupId>
		    <artifactId>mybatis-generator-core</artifactId>
		    <version>1.4.2</version>
		</dependency>
    </dependencies>

    <build>
    	<!--<finalName>struts2-archetype-starter</finalName>-->
        <finalName>StrutsApp</finalName>
        <plugins>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.4.46.v20220331</version>
                <configuration>
                    <stopKey>CTRL+C</stopKey>
                    <stopPort>8999</stopPort>
                    <scanIntervalSeconds>10</scanIntervalSeconds>
                    <webAppSourceDirectory>${basedir}/src/main/webapp/</webAppSourceDirectory>
                    <webAppConfig>
                        <contextPath>/StrutsApp</contextPath>
                        <descriptor>${basedir}/src/main/webapp/WEB-INF/web.xml</descriptor>
                    </webAppConfig>
                </configuration>
            </plugin>
            <!--MyBatis追加-->
			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.4.1</version>
				<configuration>
					<configurationFile>${project.basedir}/src/main/resources/generatorConfig.xml</configurationFile>
					<overwrite>true</overwrite>
					<includeAllDependencies>true</includeAllDependencies>
				</configuration>
			</plugin>
        </plugins>
    </build>
</project>

MyBatisコマンドでEntity、Mapperを自動生成

いよいよ、MyBatisコマンドを使って自動生成していきます。

下記のコマンドを入力してください。

mvn mybatis-generator:generate

下記のようにコマンド表示されれば完成です。
image.png

ディレクトリには、下記のようにEntityとMapperが自動生成されます。
image.png

サイト

【Java】MariaDB(MySQL)とSpringBoot(ver4系)でMyBatisGeneratorを使ってEntityとMapperとXML を自動生成する

Mavenライブラリについて

MySQL Connector

MyBatis

MyBatis Generator Core

トラブルシューティング

generatorConfig.xmlでエラーが出る

(原因)
だいたいの原因が、エラーの原因は XML の構造が MyBatis Generator の仕様と違うことです。
<context> 要素が抜けていないかを確認してください。
Eclipse が場所を示せないのは、DTDレベルの構造エラーだからです。

🔍 なぜ が必要なのか
MyBatis Generator は:
■DB種類
■Runtime(MyBatis3)
■出力ルール
<context> 単位で管理します。
DTD上、

generatorConfiguration
 └─ context(必須)
     ├─ jdbcConnection
     ├─ javaModelGenerator
     ├─ table

という構造が絶対条件です。

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