MyBatisを使って、entity,daoを自動で作成する。
■mavenプロジェクト作成
(pom.xml修正:mybatis、generator定義、generator拡張時は、拡張クラスを定義)、
■maven-install
■generator(拡張pluginがある場合、plugin定義), mybatis用xml定義
■generator拡張クラス作成
■maven-build(ゴール追加:generator..)
generatorによって、Dao(Mapper, Mapper.xml), Entityクラスが自動生成される。
※build前にDB環境構築(該当テーブル生成して置く)
---------------------------------------------------------------------
■mavenプロジェクト作成
1.mavenプロジェクト作成
2.pom.xml修正
下記追加
---------------------------------------------------------------
<!-- 追加1 start ※</dependencies>前に-->
<!-- http://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.0</version>
</dependency>
<!-- 追加1 end -->
<!-- 追加3 mybatis generator pluginを使うため start -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.6</version>
</dependency>
<!-- 追加3 end -->
</dependencies>
<!-- 追加2 starat ※ </project>前に-->
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.1</version>
<!-- 追加2 end -->
<!-- 私のjar(generatorをカスタムしたplugin)を追加 -->
<dependencies>
<dependency>
<groupId>com.mybatis2.plugin</groupId>
<artifactId>plugin</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
</plugin>
<!-- 私のjar end -->
<!-- C:\Users\user\.m2\repository\com\mybatis\plugin\plugin\1.0.0\plugin-1.0.0.jar プラグインのクラスパスを認識させるため、カスタムpluginクラスのjar作成し、こちらの場所に配置しておく-->
</plugins>
</build>
</project>
-----------------------------------------------------------------------
■maven-install
3.Maven Install
C:\Users\user\.m2\repositoryにinstallされたこと確認
Maven依存関係
mybatis-3.4.0.jar ー--> 追加されたこと確認
■generator(拡張pluginがある場合、plugin定義), mybatis用xml定義
4. resources追加(src/main/resources/)
・mybatis-config.xml,
・generatorConfig.xml
------------- mybatis-config.xml ---------------------------------------
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- JDBCの設定です(1) -->
<environments default="gissn">
<environment id="gissn">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:XE" />
<property name="username" value="gissn" />
<property name="password" value="oracle" />
</dataSource>
</environment>
</environments>
<!-- mapperパッケージを指定します -->
<mappers>
<package name="com.example.dao" />
</mappers>
</configuration>
-----------------------------generatorConfig-------------------------------------
xxx.xxx.xx.x --> localhost
<?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>
<classPathEntry location="C:\work\tools\oracle\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc6.jar" />
<context id="context1" targetRuntime="MyBatis3">
<!-- ★com.mybatis2パッケージに拡張pluginクラスがあるか 確認! start -->
<plugin type="com.mybatis.plugin.MapperClassNamePlugin" />
<plugin type="com.mybatis.plugin.BeanClassNamePlugin" />
<!-- ★com.mybatis2パッケージに拡張pluginクラスがあるか 確認! end -->
<!-- JDBCの設定です (1) -->
<jdbcConnection
driverClass="oracle.jdbc.driver.OracleDriver"
connectionURL="jdbc:oracle:thin:@localhost:1521:XE"
userId="gissn"
password="oracle"
/>
<!-- 自動生成するエンティティの設定です (2) -->
<javaModelGenerator
targetPackage="com.example.entity"
targetProject="src/main/java/"
/>
<sqlMapGenerator
targetPackage="com.example.dao"
targetProject="src/main/java/"
/>
<javaClientGenerator
targetPackage="com.example.dao"
targetProject="src/main/java/"
type="XMLMAPPER"
/>
<!-- 生成対象のテーブルです(3) -->
<table schema="gissn" tableName="%" />
</context>
</generatorConfiguration>
-------------------------------------------------
■generator拡張クラス作成
----BeanClassNamePlugin (~Entityクラス名にするためプラグインクラス作成)---------
package com.mybatis.plugin;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
/**
* MyBatis Generatorで生成するクラス名を変更するプラグイン。
*/
public class BeanClassNamePlugin extends PluginAdapter {
public boolean validate(List<String> warnings) {
return true;
}
@Override
public void initialized(IntrospectedTable table) {
super.initialized(table);
table.setBaseRecordType(table.getBaseRecordType() + "Entity");
table.setExampleType(replace(table.getExampleType(), "Example", "Filter") );
}
private String replace(String target, String search, String replace) {
Pattern pattern = Pattern.compile(search);
Matcher matcher = pattern.matcher(target);
target = matcher.replaceAll(replace);
return target;
}
}
---MapperClassNamePlugin (MapperクラスをDaoクラウス名に生成させるため)--------
package com.mybatis.plugin;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
public class MapperClassNamePlugin extends PluginAdapter {
public boolean validate(List<String> warnings) {
return true;
}
@Override
public void initialized(IntrospectedTable introspectedTable) {
introspectedTable.setMyBatis3JavaMapperType(replace(introspectedTable.getMyBatis3JavaMapperType(), "Mapper", "Dao"));//~Mapper.java を変更
introspectedTable.setMyBatis3XmlMapperFileName(replace(introspectedTable.getMyBatis3XmlMapperFileName(), "Mapper", "Dao")); //~Mapper.xml を変更
}
private String replace(String target, String search, String replace) {
Pattern pattern = Pattern.compile(search);
Matcher matcher = pattern.matcher(target);
target = matcher.replaceAll(replace);
return target;
}
}
※pluginクラスをjarでエクスポートし、pom.xml定義場所に配置
ex)C:\Users\user\.m2\repository\com\mybatis2\plugin\plugin\1.0.0\plugin-1.0.0.jar
----------------------------------------------------
■maven-build(ゴール追加:generator..)
6.maven ビルドに新規追加し、実行
・基底ディレクトリーにmavenプロジェクトのワークスペースを設定
・ゴール設定:mybatis-generator:generate
7. 設定path通り、entity,daoが作成されていればOK
------------------------------------------------------------------
-------------------------------------------------------
■sqlログ出力するため、pom.xmlにlog4j.jar定義
-----------pom.xml--------------------------------------------
<!-- 追加4 log4j -->
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- 追加4 log4j end -->
---------------------------------------------------
※Log4j.propertiesを使う
resources直下に配置
log4j.xmlが存在したら、xmlを優先にするため、注意
mybatisのsqlログを出力したい場合:下記のlog4j.logger.com.example.dao=DEBUG
特定のDaoクラスを定義も可能log4j.logger.com.example.dao.Test1Dao=DEBUG
------------------Log4j.properties-----------------------------------
# Global logging configuration
#log4j.logger.java.sql=DEBUG
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.example.dao=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
------------------------------------------------------------------------------
■insertとinsertSelectiveの違い
insert:
insert項目がすべて指定されてsql発行される。
・パラメータを指定しなかった場合、nullが指定されてしまう。
ex)
Test1Entity entity = new Test1Entity();
entity.setCol1("insert_1");
entity.setCol2("1");
int result = dao.insert(entity);
実行結果LOG
DEBUG [main] - ==> Preparing: insert into GISSN.TEST1 (COL1, COL2, COL3 ) values (?, ?, ? )
DEBUG [main] - ==> Parameters: insert_1(String), 1(String), null
DEBUG [main] - <== Updates: 1
insertSelective:
insert項目が指定した項目のみ、指定されてsql発行される。
・パラメータを指定しなかった場合、insert項目に指定されない。
・null設定してもinsert項目に指定されない。
ex)
Test1Entity entity = new Test1Entity();
entity.setCol1("insertSv_1");
entity.setCol2("1");
int result = dao.insertSelective(entity);
実行結果LOG
DEBUG [main] - ==> Preparing: insert into GISSN.TEST1 ( COL1, COL2 ) values ( ?, ? )
DEBUG [main] - ==> Parameters: insertSv_1(String), 1(String)
DEBUG [main] - <== Updates: 1
テーブルTEST1確認
※col3は、default '0':insertメソッドではデフォルト指定カラムがある場合、指定しないとdefault値でinsertできない。null指定したら、nullでinsert。defaultカラムが存在した場合、insertSelectiveメソッドを使った方がいいかもしれない。
--------------------------------------
col1 col2 col3
--------------------------------------
insert_1 1 (NULL)
insertSv_1 1 0
--------------------------------------
■updateByPrimaryKeyとupdateByPrimaryKeySelective
・updateByPrimaryKeyメソッド
PK以外のすべての項目を更新する。
設定しない項目は、nullで更新されてしまう。(updateのset文に設定しない項目も追加され、さらにnullで更新)
ex)col4は、設定してない
Test1Entity entity = new Test1Entity();
entity.setCol1("key1");
entity.setCol2("key2");
entity.setCol3("col3");
int result = dao.updateByPrimaryKey(entity);
実行結果LOG
DEBUG [main] - ==> Preparing: update GISSN.TEST1
set COL3 = ?, COL4 = ? where COL1 = ? and COL2 = ?
DEBUG [main] - ==> Parameters:
col3(String), null, insert1(String), (String)
DEBUG [main] - <== Updates: 1
・ updateByPrimaryKeySelectiveメソッド
PK以外の設定した項目のみ更新する。
nullで設定した項目は更新されない。(updateのset文に追加されない)
ex)col4は、設定してない
Test1Entity entity = new Test1Entity();
entity.setCol1("key1");
entity.setCol2("key2");
entity.setCol3("col3");
int result = dao.updateByPrimaryKeySelective(entity);
実行結果LOG
DEBG [main] - ==> Preparing: update GISSN.TEST1
SET COL3 = ? where COL1 = ? and COL2 = ?
DEBUG [main] - ==>
Parameters: col3(String), insertSv1(String), (String)
DEBUG [main] - <== Updates: 1