今回は、DB操作フレームワークであるMyBatisの自動生成機能についてのメモです。
MyBatisの基本的な部分についてはあまり触れておりませんので、ご了承下さい。
目次
検証環境・バージョン
- MacOS:Sonoma 14.6
- Amazon Corretto:17
- SpringBoot:3.4.0
- MyBatis:3.0.4
- MyBatis generator-core:1.4.0
- IntelliJ IDEA:2024.2 (Ultimate Edition)
ビルド設定(Gradle)
はじめにモジュール依存設定を行います。基本的なMyBatisの設定以外にも、
MyBatis Generatorの設定が必要です。
MyBatis基本・Generator関連ライブラリ
dependencies {
// SpringbootでMyBatisを使用するための統合ライブラリ
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.4'
// DB接続ドライバー
runtimeOnly 'com.mysql:mysql-connector-j'
// MyBatis Generatorのコアライブラリ
mybatisGenerator 'org.mybatis.generator:mybatis-generator-core:1.4.0'
// MyBatis Generatorが必要とするMySQL用のJDBCドライバ
mybatisGenerator 'com.mysql:mysql-connector-j'
}
MyBatis Generatorの実行タスク追加
// MyBatis Generator用の依存関係を定義するカスタム構成
configurations {
mybatisGenerator
}
// 'mybatisGenerator'という名前のタスクを登録します
tasks.register('mybatisGenerator') {
// タスクの実行内容を定義します
doLast {
// Antタスクを定義します。'mbgenerator'という名前で、クラスパスに'mybatisGenerator'構成のパスを設定します
ant.taskdef(name: 'mbgenerator', classname: 'org.mybatis.generator.ant.GeneratorAntTask', classpath: configurations.mybatisGenerator.asPath)
// MyBatis Generatorタスクを実行します。設定ファイルは'src/main/resources/mybatis/generatorConfig.xml'とし、自動生成ファイルの上書きと詳細出力を有効にします
ant.mbgenerator(overwrite: true, configfile: 'src/main/resources/mybatis/generatorConfig.xml', verbose: true)
}
}
尚、タスク名は任意の名称を登録できます。
また、設定ファイルのパスも指定と配置の整合性が合っていれば、環境に応じて変更可能です。
MyBatis 自動生成 設定ファイル作成
次に、MyBatis Generatorの設定ファイル(前述の記述ですとgeneratorConfig.xml)を作成します。
設定ファイルでは以下を定義します。
- DB接続設定
- 自動生成するmodelクラスの配置場所
- 自動生成するXML形式のmapperファイルの配置場所
- 自動生成するmapperインターフェースの配置場所
- 自動生成する対象のDBテーブル
設定は色々なオプションが有り、細かな調整をこちらで指定することができます。
詳しくは公式ページを参照下さい。
https://mybatis.org/generator/configreference/xmlconfig.html
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>
<!-- DB接続設定 -->
<context id="MyBatis3" targetRuntime="MyBatis3">
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3497/test_db"
userId="test_db_docker"
password="test_db_docker_pass"/>
<!-- Javaモデル生成 -->
<javaModelGenerator targetPackage="com.springbootmybatis.model" targetProject="src/main/java"/>
<!-- Mapper XML生成 -->
<sqlMapGenerator
targetPackage="mapper"
targetProject="src/main/resources/mybatis"/>
<!-- Mapperインターフェース生成 -->
<javaClientGenerator
type="XMLMAPPER"
targetPackage="com.springbootmybatis.mapper"
targetProject="src/main/java"/>
<!-- テーブル指定 -->
<table tableName="user" domainObjectName="User"/>
</context>
</generatorConfiguration>
xmlのファイル名称を任意の文字列に指定したい場合、application.propertiesに指定を入れます。
ワイルドカードで指定すればどんな文字列でも対応可能になります。
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
SpringBootApplicationクラス MyBatisマッパー指定
次に、SpringBootApplicationの基底クラスに、
@MapperScan
というアノテーションを付与します。
@MapperScan("com.springbootmybatis.mapper")
こちらを付与することにより、MyBatisのMapperインターフェースを自動的に検出し、Springコンテナに登録します。
全体例
package com.springbootmybatis;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.springbootmybatis.mapper")
public class SpringbootMyBatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMyBatisApplication.class, args);
}
}
MyBatis Generator
そして、準備ができたら自動生成機能を利用して、
mapperクラス、mapperインターフェース、mapper xmlファイルを作成します。
前述までの設定に加えてデータベースに接続可能な状態にして、
設定ファイル(generator_config.xml)ファイルで指定したDBテーブルが、データベースに用意されている状態にします。
その後、登録済みの自動生成用gradleタスクを実行します。
コマンドで実行するか、IDEの機能などで実装します。
./gradlew mybatisGenerator
自動生成タスクを実行すると、3つのフォルダが自動生成され、それぞれの役割のファイルが生成されます。
・src/main/java/mapper(Mapper.xmlに対応したメソッドが定義されたインターフェース)
・src/main/java/model(DBテーブルの内容を定義したクラス)
・src/main/resources(DB操作を行うSQLが定義されたXMLファイル)
これらの配置場所なども、先述のMyBatis Generatorの設定ファイルで設定可能です。
Mapperインターフェース
一つ目は、XMLで定義されたSQLを実行するための接続処理が定義されたインターフェースです。
こちらで宣言されているメソッド名がmapper xmlでidとして定義されています。
package com.springbootmybatis.mapper;
import com.springbootmybatis.model.User;
import com.springbootmybatis.model.UserExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface UserMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
long countByExample(UserExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
int deleteByExample(UserExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
int insert(User record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
int insertSelective(User record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
List selectByExample(UserExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
User selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
int updateByExample(@Param("record") User record, @Param("example") UserExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
int updateByPrimaryKeySelective(User record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
int updateByPrimaryKey(User record);
}
Modelクラス
二つ目のファイルは、DBテーブルの内容が定義されたクラスです。
SQLの実行結果などがこちらのクラスの形で取得されます。
package com.springbootmybatis.model;
public class User {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.id
*
* @mbg.generated Sun Dec 08 01:48:57 JST 2024
*/
private Integer id;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.name
*
* @mbg.generated Sun Dec 08 01:48:57 JST 2024
*/
private String name;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.age
*
* @mbg.generated Sun Dec 08 01:48:57 JST 2024
*/
private Integer age;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.id
*
* @return the value of user.id
*
* @mbg.generated Sun Dec 08 01:48:57 JST 2024
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.id
*
* @param id the value for user.id
*
* @mbg.generated Sun Dec 08 01:48:57 JST 2024
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.name
*
* @return the value of user.name
*
* @mbg.generated Sun Dec 08 01:48:57 JST 2024
*/
public String getName() {
return name;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.name
*
* @param name the value for user.name
*
* @mbg.generated Sun Dec 08 01:48:57 JST 2024
*/
public void setName(String name) {
this.name = name;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.age
*
* @return the value of user.age
*
* @mbg.generated Sun Dec 08 01:48:57 JST 2024
*/
public Integer getAge() {
return age;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.age
*
* @param age the value for user.age
*
* @mbg.generated Sun Dec 08 01:48:57 JST 2024
*/
public void setAge(Integer age) {
this.age = age;
}
}
参考用のexampleクラスも生成されます。
package com.springbootmybatis.model;
import java.util.ArrayList;
import java.util.List;
public class UserExample {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
protected boolean distinct;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
protected List oredCriteria;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
public UserExample() {
oredCriteria = new ArrayList<>();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
public String getOrderByClause() {
return orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
public boolean isDistinct() {
return distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
public List getOredCriteria() {
return oredCriteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
protected abstract static class GeneratedCriteria {
protected List criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List getAllCriteria() {
return criteria;
}
public List getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andNameIsNull() {
addCriterion("name is null");
return (Criteria) this;
}
public Criteria andNameIsNotNull() {
addCriterion("name is not null");
return (Criteria) this;
}
public Criteria andNameEqualTo(String value) {
addCriterion("name =", value, "name");
return (Criteria) this;
}
public Criteria andNameNotEqualTo(String value) {
addCriterion("name <>", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThan(String value) {
addCriterion("name >", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThanOrEqualTo(String value) {
addCriterion("name >=", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThan(String value) {
addCriterion("name <", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThanOrEqualTo(String value) {
addCriterion("name <=", value, "name");
return (Criteria) this;
}
public Criteria andNameLike(String value) {
addCriterion("name like", value, "name");
return (Criteria) this;
}
public Criteria andNameNotLike(String value) {
addCriterion("name not like", value, "name");
return (Criteria) this;
}
public Criteria andNameIn(List values) {
addCriterion("name in", values, "name");
return (Criteria) this;
}
public Criteria andNameNotIn(List values) {
addCriterion("name not in", values, "name");
return (Criteria) this;
}
public Criteria andNameBetween(String value1, String value2) {
addCriterion("name between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andNameNotBetween(String value1, String value2) {
addCriterion("name not between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andAgeIsNull() {
addCriterion("age is null");
return (Criteria) this;
}
public Criteria andAgeIsNotNull() {
addCriterion("age is not null");
return (Criteria) this;
}
public Criteria andAgeEqualTo(Integer value) {
addCriterion("age =", value, "age");
return (Criteria) this;
}
public Criteria andAgeNotEqualTo(Integer value) {
addCriterion("age <>", value, "age");
return (Criteria) this;
}
public Criteria andAgeGreaterThan(Integer value) {
addCriterion("age >", value, "age");
return (Criteria) this;
}
public Criteria andAgeGreaterThanOrEqualTo(Integer value) {
addCriterion("age >=", value, "age");
return (Criteria) this;
}
public Criteria andAgeLessThan(Integer value) {
addCriterion("age <", value, "age");
return (Criteria) this;
}
public Criteria andAgeLessThanOrEqualTo(Integer value) {
addCriterion("age <=", value, "age");
return (Criteria) this;
}
public Criteria andAgeIn(List values) {
addCriterion("age in", values, "age");
return (Criteria) this;
}
public Criteria andAgeNotIn(List values) {
addCriterion("age not in", values, "age");
return (Criteria) this;
}
public Criteria andAgeBetween(Integer value1, Integer value2) {
addCriterion("age between", value1, value2, "age");
return (Criteria) this;
}
public Criteria andAgeNotBetween(Integer value1, Integer value2) {
addCriterion("age not between", value1, value2, "age");
return (Criteria) this;
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table user
*
* @mbg.generated do_not_delete_during_merge Sun Dec 15 23:11:21 JST 2024
*/
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table user
*
* @mbg.generated Sun Dec 15 23:11:21 JST 2024
*/
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
Mapper XMLファイル
最後の自動生成ファイルは、実行するSQLを定義するXMLファイルです。
プロジェクトの構成にもよりますが、こちらは外出しすることにより、
サービスを停止することなく実行SQLを変更することなどもできます。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.springbootmybatis.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.springbootmybatis.model.User">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sun Dec 15 23:11:21 JST 2024.
-->
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="age" jdbcType="INTEGER" property="age" />
</resultMap>
<sql id="Example_Where_Clause">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sun Dec 15 23:11:21 JST 2024.
-->
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue"> and ${criterion.condition} </when>
<when test="criterion.singleValue"> and ${criterion.condition} #{criterion.value} </when>
<when test="criterion.betweenValue"> and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when>
<when test="criterion.listValue"> and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} </foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sun Dec 15 23:11:21 JST 2024.
-->
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue"> and ${criterion.condition} </when>
<when test="criterion.singleValue"> and ${criterion.condition} #{criterion.value} </when>
<when test="criterion.betweenValue"> and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when>
<when test="criterion.listValue"> and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} </foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sun Dec 15 23:11:21 JST 2024.
--> id, name, age
</sql>
<select id="selectByExample" parameterType="com.springbootmybatis.model.UserExample" resultMap="BaseResultMap">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sun Dec 15 23:11:21 JST 2024.
-->
select
<if test="distinct"> distinct </if>
<include refid="Base_Column_List" />
from user
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null"> order by ${orderByClause} </if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sun Dec 15 23:11:21 JST 2024.
-->
select
<include refid="Base_Column_List" />
from user where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sun Dec 15 23:11:21 JST 2024.
-->
delete from user where id = #{id,jdbcType=INTEGER}
</delete>
<delete id="deleteByExample" parameterType="com.springbootmybatis.model.UserExample">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sun Dec 15 23:11:21 JST 2024.
-->
delete from user
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.springbootmybatis.model.User">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sun Dec 15 23:11:21 JST 2024.
-->
insert into user (id, name, age )
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER} )
</insert>
<insert id="insertSelective" parameterType="com.springbootmybatis.model.User">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sun Dec 15 23:11:21 JST 2024.
-->
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null"> id, </if>
<if test="name != null"> name, </if>
<if test="age != null"> age, </if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null"> #{id,jdbcType=INTEGER}, </if>
<if test="name != null"> #{name,jdbcType=VARCHAR}, </if>
<if test="age != null"> #{age,jdbcType=INTEGER}, </if>
</trim>
</insert>
<select id="countByExample" parameterType="com.springbootmybatis.model.UserExample" resultType="java.lang.Long">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sun Dec 15 23:11:21 JST 2024.
-->
select count(*) from user
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sun Dec 15 23:11:21 JST 2024.
-->
update user
<set>
<if test="record.id != null"> id = #{record.id,jdbcType=INTEGER}, </if>
<if test="record.name != null"> name = #{record.name,jdbcType=VARCHAR}, </if>
<if test="record.age != null"> age = #{record.age,jdbcType=INTEGER}, </if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sun Dec 15 23:11:21 JST 2024.
-->
update user
set id = #{record.id,jdbcType=INTEGER}, name = #{record.name,jdbcType=VARCHAR}, age = #{record.age,jdbcType=INTEGER}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.springbootmybatis.model.User">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sun Dec 15 23:11:21 JST 2024.
-->
update user
<set>
<if test="name != null"> name = #{name,jdbcType=VARCHAR}, </if>
<if test="age != null"> age = #{age,jdbcType=INTEGER}, </if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.springbootmybatis.model.User">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sun Dec 15 23:11:21 JST 2024.
-->
update user set name = #{name,jdbcType=VARCHAR}, age = #{age,jdbcType=INTEGER} where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
DBデータ取得用API 実装
最後に、以下は簡単なDBテーブルからSELECT文を実行してデータを取得する例です。
自動生成されたファイルを利用すれば、簡単なCRUDぐらいの操作であればそのまま実装可能です。
package com.springbootmybatis.service;
import com.springbootmybatis.mapper.UserMapper;
import com.springbootmybatis.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service public class UserService {
@Autowired
private UserMapper userMapper;
@Transactional(readOnly = true)
public List<User> getAllUsers() {
return userMapper.selectByExample(null);
}
}
今回は以上となります。
あくまでも自動生成されるファイルは定型的なパターンのみなので、
多くの場合自作する必要が出てくると思います。
しかし、その場合でもどのような実装にするか参考になりますし、
基礎部分をコピーして利用できると思います。