前言
MyBatis官方提供了MyBatis Generator插件用来生成model、mapper和xml,但是如果在生成代码的时候想加入一些自定义的内容,也就是plugin,就要把自定义的内容打成包,再把配置放到MyBatis Generator插件里才行,这样相当麻烦。于是采用JAVA执行MyBatis Generator的方法就不需要再打成包了。
开始配置
generatorConfig.xml
JSR303Plugin是自定义的内容
<?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>
<!-- 引入配置文件 -->
<properties resource="generatorConfig.properties"/>
<!-- 数据库驱动 -->
<!--classPathEntry location="${classPath}"/-->
<!-- 数据库驱动 -->
<classPathEntry location="${db.oracle.kf.classPath}"/>
<!-- oralce -->
<context id="oracle" targetRuntime="MyBatis3" defaultModelType="flat">
<property name="javaFileEncoding" value="UTF-8"/>
<!-- This plugin is only valid for MyBatis3 target runtime -->
<plugin type="org.mybatis.generator.plugins.RowBoundsPlugin" />
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<plugin type="com.asiainfo.aigov.fdapp.common.JSR303Plugin" />
<!-- 数据库连接 -->
<jdbcConnection
driverClass="${db.oracle.kf.driverClass}"
connectionURL="${db.oracle.kf.jdbcUrl}"
userId="${db.oracle.kf.user}"
password="${db.oracle.kf.password}">
<!-- 针对oracle数据库 -->
<property name="remarksReporting" value="true"></property>
<!-- 针对mysql数据库 -->
<property name="useInformationSchema" value="true"></property>
</jdbcConnection>
<!-- model -->
<javaModelGenerator
targetPackage="${targetPackage}.model"
targetProject="${targetProject}" />
<!-- mapper.xml -->
<sqlMapGenerator
targetPackage="${targetPackage}.dao.mapper.oracle"
targetProject="${targetProject}" />
<!-- dao或mapper接口 -->
<javaClientGenerator
targetPackage="${targetPackage}.dao"
targetProject="${targetProject}"
type="XMLMAPPER" />
<!-- 表配置 -->
<table tableName="FD_ATTENTION" domainObjectName="" />
</context>
</generatorConfiguration>
generatorConfig.properties
#oralce
db.oracle.kf.driverClass=oracle.jdbc.driver.OracleDriver
db.oracle.kf.jdbcUrl=数据库链接
db.oracle.kf.user=用户名
db.oracle.kf.password=密码
db.oracle.kf.classPath=/Users/pany/.m2/repository/com/oracle/ojdbc14/10.2.0.4.0/ojdbc14-10.2.0.4.0.jar
#这里要用全路径
targetProject=/Users/pany/Documents/workspace/aigov/familydoctor-webapp/src/main/java
targetPackage=com.asiainfo.aigov.familydoctor
JSR303Plugin
package com.asiainfo.aigov.fdapp.common;
import java.util.List;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.TopLevelClass;
/**
* 功能描述:jsr303 代码生成插件
*/
public class JSR303Plugin extends PluginAdapter {
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass,
IntrospectedTable introspectedTable) {
// 增加类注解
topLevelClass.addImportedType("io.swagger.annotations.ApiModel");
topLevelClass.addAnnotation("@ApiModel");
return super.modelBaseRecordClassGenerated(topLevelClass, introspectedTable);
}
@Override
public boolean modelFieldGenerated(Field field,
TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn,
IntrospectedTable introspectedTable, ModelClassType modelClassType) {
if (false == introspectedColumn.isNullable()) {
if (false == introspectedColumn.isIdentity()) {
boolean isPrimarkKey = false;//是否为主键
for(IntrospectedColumn column : introspectedTable.getPrimaryKeyColumns()) {
if(introspectedColumn==column) {
isPrimarkKey = true;
}
}
if(!isPrimarkKey) {
topLevelClass.addImportedType("javax.validation.constraints.NotNull");
field.addAnnotation("@NotNull");
}
}
}
if (introspectedColumn.isStringColumn()) {
topLevelClass.addImportedType("io.swagger.annotations.ApiModelProperty");
field.addAnnotation("@ApiModelProperty(\"" + introspectedColumn.getRemarks() + "\")");
topLevelClass.addImportedType("javax.validation.constraints.Size");
field.addAnnotation("@Size(min = 0, max = " + introspectedColumn.getLength() + " , message = \"长度必须在{min}和{max}之间\")");
} else if ("DECIMAL".equals(introspectedColumn.getJdbcTypeName())) {
topLevelClass.addImportedType("io.swagger.annotations.ApiModelProperty");
field.addAnnotation("@ApiModelProperty(value=\"" + introspectedColumn.getRemarks() + "\", example=\"0\")");
}
return super.modelFieldGenerated(field, topLevelClass, introspectedColumn,
introspectedTable, modelClassType);
}
@Override
public boolean validate(List<String> warnings) {
return true;
}
}
MyBatisGenTest
右键执行单元测试即可
package com.asiainfo.aigov;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.api.ProgressCallback;
import org.mybatis.generator.api.VerboseProgressCallback;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyBatisGenTest {
@Test
public void gen() {
//读取文件
File configFile = new File(this.getClass().getClassLoader().getResource("generatorConfig.xml").getFile());
List<String> warnings = new ArrayList<String>();
ConfigurationParser cp = new ConfigurationParser(warnings);
//true:覆盖生成
DefaultShellCallback callback = new DefaultShellCallback(true);
try {
Configuration config = cp.parseConfiguration(configFile);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
ProgressCallback progressCallback = new VerboseProgressCallback();
myBatisGenerator.generate(progressCallback);
System.out.println("代码成功生成!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
结后语
略