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】Sprint BootとMyBatis Generaterを使ってPostgreSQLのテーブルからクラスを自動生成する方法

Last updated at Posted at 2025-08-02

ディレクトリ構成

image.png

テーブル作成

MyBatisはテーブルからコードを生成するため、あらかじめテーブルを作成しておきましょう。
image.png

Spring Bootプロジェクトの新規作成

Eclipseのメニュー画面から「Springスタータープロジェクト」を選択します。
image.png

今回は、下記のツールを依存関係としました。
image.png

ファイルの更新

pom.xmlの更新

Mavenツールのmybatis-spring-boot-starterとMavenプラグインspring-boot-maven-pluginを追記していきます。

全体のコードはこちら⇩

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.5.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.packt.cardatabase</groupId>
	<artifactId>SpringBootPostgresMybatis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBootPostgresMybatis</name>
	<description>Demo project for Spring Boot</description>
	<url/>
	<licenses>
		<license/>
	</licenses>
	<developers>
		<developer/>
	</developers>
	<scm>
		<connection/>
		<developerConnection/>
		<tag/>
		<url/>
	</scm>
	<properties>
		<java.version>17</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.postgresql</groupId>
			<artifactId>postgresql</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
		<dependency>
		    <groupId>org.mybatis.spring.boot</groupId>
		    <artifactId>mybatis-spring-boot-starter</artifactId>
		    <version>3.0.5</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<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>

application.propertiesの更新

つぎは、データベースの接続情報を入力していきます。

src/main/resources/application.properties
spring.application.name=<プロジェクト名>👈自動で入る
spring.datasource.url=jdbc:postgresql://localhost:5432/<データベース名>
spring.datasource.username=<ユーザー名>
spring.datasource.password=<パスワード>

generatorConfig.xmlを新規作成と更新

MyBatisGeneraterの設定ファイルを新規で作成し、下記のように更新します。

src/main/resources/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="tables" targetRuntime="MyBatis3Simple">
        <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
        <plugin type="org.mybatis.generator.plugins.MapperAnnotationPlugin"/>

        <jdbcConnection
                driverClass="org.postgresql.Driver"
                connectionURL="jdbc:postgresql://localhost:5432/<データベース名>"
                userId="<ユーザー名>"
                password="<パスワード>"/>

        <javaModelGenerator
                targetPackage="com.example.spring.mybatis.model"
                targetProject="src/main/java"/>
        <sqlMapGenerator
                targetPackage="com.example.spring.mybatis.mapper"
                targetProject="src/main/resources"/>
        <javaClientGenerator
                type="XMLMAPPER"
                targetPackage="com.example.spring.mybatis.mapper"
                targetProject="src/main/java"/>

        <table tableName="<テーブル名>">
            <generatedKey column="id" sqlStatement="JDBC"/>
        </table>
    </context>
</generatorConfiguration>

コード生成

プロジェクトの上で右クリック⇒[コマンドプロンプト]を選択します。
image.png

プロンプト上で下記のコマンドを実行します。

$ mvn mybatis-generator:generate

下記のように表示された成功です。
image.png

下記のようにクラスが自動生成されます。

User.java
package com.example.spring.mybatis.model;

import java.util.Date;

public class Users {
    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column users.id
     *
     * @mbg.generated Sat Aug 02 17:20:59 GMT+09:00 2025
     */
    private Integer id;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column users.name
     *
     * @mbg.generated Sat Aug 02 17:20:59 GMT+09:00 2025
     */
    private String name;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column users.email
     *
     * @mbg.generated Sat Aug 02 17:20:59 GMT+09:00 2025
     */
    private String email;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column users.created_at
     *
     * @mbg.generated Sat Aug 02 17:20:59 GMT+09:00 2025
     */
    private Date createdAt;

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column users.id
     *
     * @return the value of users.id
     *
     * @mbg.generated Sat Aug 02 17:20:59 GMT+09:00 2025
     */
    public Integer getId() {
        return id;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column users.id
     *
     * @param id the value for users.id
     *
     * @mbg.generated Sat Aug 02 17:20:59 GMT+09:00 2025
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column users.name
     *
     * @return the value of users.name
     *
     * @mbg.generated Sat Aug 02 17:20:59 GMT+09:00 2025
     */
    public String getName() {
        return name;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column users.name
     *
     * @param name the value for users.name
     *
     * @mbg.generated Sat Aug 02 17:20:59 GMT+09:00 2025
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column users.email
     *
     * @return the value of users.email
     *
     * @mbg.generated Sat Aug 02 17:20:59 GMT+09:00 2025
     */
    public String getEmail() {
        return email;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column users.email
     *
     * @param email the value for users.email
     *
     * @mbg.generated Sat Aug 02 17:20:59 GMT+09:00 2025
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column users.created_at
     *
     * @return the value of users.created_at
     *
     * @mbg.generated Sat Aug 02 17:20:59 GMT+09:00 2025
     */
    public Date getCreatedAt() {
        return createdAt;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column users.created_at
     *
     * @param createdAt the value for users.created_at
     *
     * @mbg.generated Sat Aug 02 17:20:59 GMT+09:00 2025
     */
    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table users
     *
     * @mbg.generated Sat Aug 02 17:20:59 GMT+09:00 2025
     */
    @Override
    public boolean equals(Object that) {
        if (this == that) {
            return true;
        }
        if (that == null) {
            return false;
        }
        if (getClass() != that.getClass()) {
            return false;
        }
        Users other = (Users) that;
        return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
            && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName()))
            && (this.getEmail() == null ? other.getEmail() == null : this.getEmail().equals(other.getEmail()))
            && (this.getCreatedAt() == null ? other.getCreatedAt() == null : this.getCreatedAt().equals(other.getCreatedAt()));
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table users
     *
     * @mbg.generated Sat Aug 02 17:20:59 GMT+09:00 2025
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
        result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
        result = prime * result + ((getEmail() == null) ? 0 : getEmail().hashCode());
        result = prime * result + ((getCreatedAt() == null) ? 0 : getCreatedAt().hashCode());
        return result;
    }
}
UsersMapper.java
package com.example.spring.mybatis.mapper;

import com.example.spring.mybatis.model.Users;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UsersMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table users
     *
     * @mbg.generated Sat Aug 02 17:20:59 GMT+09:00 2025
     */
    int deleteByPrimaryKey(Integer id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table users
     *
     * @mbg.generated Sat Aug 02 17:20:59 GMT+09:00 2025
     */
    int insert(Users row);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table users
     *
     * @mbg.generated Sat Aug 02 17:20:59 GMT+09:00 2025
     */
    Users selectByPrimaryKey(Integer id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table users
     *
     * @mbg.generated Sat Aug 02 17:20:59 GMT+09:00 2025
     */
    List<Users> selectAll();

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table users
     *
     * @mbg.generated Sat Aug 02 17:20:59 GMT+09:00 2025
     */
    int updateByPrimaryKey(Users row);
}

アプリ実行

/com.packt.cardatabase/SpringBootPostgresMyBatis.java
package com.packt.cardatabase;

import java.util.List;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.example.spring.mybatis.mapper.UsersMapper;
import com.example.spring.mybatis.model.Users;

@MapperScan("com.example.spring.mybatis.mapper")
@SpringBootApplication
public class SpringBootPostgresMybatisApplication {
	
	static UsersMapper userMapper;

	public static void main(String[] args) {
		SpringApplication.run(SpringBootPostgresMybatisApplication.class, args);
		
	}
	
	@Bean
	ApplicationRunner run(UsersMapper userMapper) {
		return args -> {
            // CommandLineRunnerと同様のロジック
            List<Users> usersList = userMapper.selectAll();
            usersList.forEach(user -> System.out.println(user.getName()));
        };
	}

}

/com.packt.cardatabase/UserDisplayRunner.java
package com.packt.cardatabase;

import java.util.List;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.example.spring.mybatis.mapper.UsersMapper;
import com.example.spring.mybatis.model.Users;

@Component
public class UserDisplayRunner implements CommandLineRunner {
	private final UsersMapper userMapper;
	
	public UserDisplayRunner(UsersMapper usermapper) {
		this.userMapper = usermapper;
	}
	
	@Override
	public void run(String...args)throws Exception {
		System.out.println("アプリケーション起動後にデータを取得して表示します。");
		List<Users> usersList = userMapper.selectAll();
		// ループ処理
        for (Users user : usersList) {
            System.out.println("ID: " + user.getId() + 
            				   ", Name: " + user.getName() + 
            				   ", Email: " + user.getEmail() +
            				   ", Create_At: " + user.getCreatedAt()
            					);
        }
	}
}

サイト

トラブルシューティング

1.データベースに関するエラー

[ERROR] Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.4.1:generate (default-cli) on project SpringBootPostgresMybatis: FATAL: ???[?U?["postgres"??p?X???[?h?F?????s??????? -> [Help 1]

[ERROR]

[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.

[ERROR] Re-run Maven using the -X switch to enable full debug logging.

[ERROR]

[ERROR] For more information about the errors and possible solutions, please read the following articles:

[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException」
(原因)

エラーメッセージ FATAL: ???[?U?["postgres"??p?X???[?h?F?????s??????? は、PostgreSQLの認証エラーが発生していることを示しています。
文字化けしていますが、これは「FATAL: ユーザー"postgres"のパスワード認証に失敗しました」という意味です。

原因は generatorConfig.xml に設定されている userId ("postgres") と password ("password") が、実際のPostgreSQLデータベースのユーザー名とパスワードと一致していないことです。

なので、application.propertiesgeneratorConfig.xmlのデータベース情報を確認しましょう。

2.「UserMapper.java]のアノテーション@Mapperの箇所でエラー「Mapper を型に解決できません」が表示される。
(原因)

@Mapper アノテーションで「Mapper を型に解決できません」というエラーが発生する主な原因は、プロジェクトのビルドパスに MyBatis-Spring-Boot-Starter の依存関係が不足していることです。

@Mapper アノテーションは、MyBatis-Spring-Bootが提供するもので、SpringアプリケーションコンテキストでこのインターフェースをMyBatisのマッパーとして認識させるために使用されます。この依存関係がないと、Javaコンパイラは @Mapper というアノテーションが何であるかを認識できず、エラーになります。

解決方法

pom.xml に MyBatis-Spring-Boot-Starter の依存関係を追加してください。

pom.xml
<dependencies>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>3.0.3</version> </dependency>
</dependencies>

3.アプリケーションエラー

Description:



Parameter 0 of constructor in com.packt.cardatabase.UserDisplayRunner required a bean of type 'com.example.spring.mybatis.mapper.UsersMapper' that could not be found.





Action:



Consider defining a bean of type 'com.example.spring.mybatis.mapper.UsersMapper' in your configuration.

このエラーは、Spring BootがUsersMapperのBeanをコンポーネントスキャンで見つけられなかったことを意味しています。

エラーの原因

ご提示のコードでは、SpringBootPostgresMybatisApplication.javaとUserDisplayRunner.javaという2つのクラスに、データベースからデータを取得するロジックが重複して書かれています。

さらに、SpringBootPostgresMybatisApplicationクラスの@Beanメソッド内でApplicationRunnerが定義されている一方で、UserDisplayRunnerは@Componentアノテーションを付けています。この場合、両方のクラスでUsersMapperが使われようとしますが、SpringはMyBatis Mapperのインターフェース自体を自動的にBeanとして登録してくれません。

MyBatisのMapperインターフェースをSpringのDIコンテナに登録するには、明示的にスキャンする必要があります。

解決方法

@MapperScan アノテーションを @SpringBootApplication を含むクラスに追加し、MyBatis Mapperが配置されているパッケージを指定することで、Springがそのパッケージ内のすべての@Mapperアノテーションが付いたインターフェースを検出し、Beanとして登録するようになります。

SpringBootPostgresMybatisApplication.java を修正する

@MapperScan を追加し、usersMapperが定義されているパッケージを指定します。また、main関数内の不要なコードと、ApplicationRunnerの@Beanメソッドを削除します。CommandLineRunnerを使うUserDisplayRunnerクラスにロジックを一本化するためです。

xxxxApplication.java
package com.packt.cardatabase;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.mybatis.spring.annotation.MapperScan;

// MyBatis Mapperが配置されているパッケージを指定
@MapperScan("com.example.spring.mybatis.mapper")
@SpringBootApplication
public class SpringBootPostgresMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootPostgresMybatisApplication.class, args);
    }
}
補足

@MapperScanアノテーションは、SpringBootPostgresMybatisApplication.javaが配置されているパッケージ(com.packt.cardatabase)よりも、Mapperのパッケージ(com.example.spring.mybatis.mapper)が下位の階層にある場合に特に有効です。

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?