MyBatis Generator原生提供的生成方式targetRuntime有幾種,但都不符合項目需求或想自定義自己的方法。
網上的文章也很多:
如:http://generator.sturgeon.mopaas.com/reference/extending.html
這裡我說下我的做法:
1、繼承IntrospectedTableMyBatis3Impl,重寫自己要改寫的方法
InsoIntrospectedTable.java
重寫calculateXmlMapperGenerator使用自己的XMLMapperGenerator
重寫createJavaClientGenerator使用自己的JavaMapperGenerator
我的做法比較粗暴,就是注釋掉原來的邏輯,自己new自己的替代原來的。
public class InsoIntrospectedTable extends IntrospectedTableMyBatis3Impl {
protected void calculateXmlMapperGenerator(AbstractJavaClientGenerator javaClientGenerator,
List<String> warnings,
ProgressCallback progressCallback) {
// if (javaClientGenerator == null) {
// if (context.getSqlMapGeneratorConfiguration() != null) {
// xmlMapperGenerator = new XMLMapperGenerator();
// }
// } else {
// xmlMapperGenerator = javaClientGenerator.getMatchedXMLGenerator();
// }
xmlMapperGenerator = new InsoXMLMapperGenerator();
initializeAbstractGenerator(xmlMapperGenerator, warnings,
progressCallback);
}
protected AbstractJavaClientGenerator createJavaClientGenerator() {
if (context.getJavaClientGeneratorConfiguration() == null) {
return null;
}
// String type = context.getJavaClientGeneratorConfiguration()
// .getConfigurationType();
AbstractJavaClientGenerator javaGenerator;
// if ("XMLMAPPER".equalsIgnoreCase(type)) { //$NON-NLS-1$
// javaGenerator = new JavaMapperGenerator();
// } else if ("MIXEDMAPPER".equalsIgnoreCase(type)) { //$NON-NLS-1$
// javaGenerator = new MixedClientGenerator();
// } else if ("ANNOTATEDMAPPER".equalsIgnoreCase(type)) { //$NON-NLS-1$
// javaGenerator = new AnnotatedClientGenerator();
// } else if ("MAPPER".equalsIgnoreCase(type)) { //$NON-NLS-1$
// javaGenerator = new JavaMapperGenerator();
// } else {
// javaGenerator = (AbstractJavaClientGenerator) ObjectFactory
// .createInternalObject(type);
// }
javaGenerator = new InsoJavaMapperGenerator();
return javaGenerator;
}
}
2、繼承XMLMapperGenerator,重寫自己要改寫的方法
InsoXMLMapperGenerator.java在getSqlMapElement方法中,可以添加或刪除自己要的方法,這裡我只添加了一個selectAll方法
public class InsoXMLMapperGenerator extends XMLMapperGenerator {
public InsoXMLMapperGenerator() {
super();
}
protected XmlElement getSqlMapElement() {
FullyQualifiedTable table = introspectedTable.getFullyQualifiedTable();
progressCallback.startTask(getString(
"Progress.12", table.toString())); //$NON-NLS-1$
XmlElement answer = new XmlElement("mapper"); //$NON-NLS-1$
String namespace = introspectedTable.getMyBatis3SqlMapNamespace();
answer.addAttribute(new Attribute("namespace", //$NON-NLS-1$
namespace));
context.getCommentGenerator().addRootComment(answer);
addResultMapWithoutBLOBsElement(answer);
addResultMapWithBLOBsElement(answer);
addExampleWhereClauseElement(answer);
addMyBatis3UpdateByExampleWhereClauseElement(answer);
addBaseColumnListElement(answer);
addBlobColumnListElement(answer);
addSelectByExampleWithBLOBsElement(answer);
addSelectByExampleWithoutBLOBsElement(answer);
addSelectByPrimaryKeyElement(answer);
addDeleteByPrimaryKeyElement(answer);
addDeleteByExampleElement(answer);
addInsertElement(answer);
addInsertSelectiveElement(answer);
addCountByExampleElement(answer);
addUpdateByExampleSelectiveElement(answer);
addUpdateByExampleWithBLOBsElement(answer);
addUpdateByExampleWithoutBLOBsElement(answer);
addUpdateByPrimaryKeySelectiveElement(answer);
addUpdateByPrimaryKeyWithBLOBsElement(answer);
addUpdateByPrimaryKeyWithoutBLOBsElement(answer);
//add select all
addSimpleSelectAllElement(answer);
return answer;
}
protected void addSimpleSelectAllElement(
XmlElement parentElement) {
if (introspectedTable.getRules()
.generateSelectByPrimaryKey()) {
AbstractXmlElementGenerator elementGenerator = new InsoSelectAllElementGenerator();
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
}
3、繼承JavaMapperGenerator,重寫自己要改寫的方法
InsoJavaMapperGenerator.java在getCompilationUnits方法中定制自己要的方法,這裡我只添加了一個selectAll方法。
注意:這裡的項要與上面的XMLMapperGenerator一一對應,其它情況,我沒有研究(比較菜。。。)
public class InsoJavaMapperGenerator extends JavaMapperGenerator {
@Override
public List<CompilationUnit> getCompilationUnits() {
progressCallback.startTask(getString("Progress.17", //$NON-NLS-1$
introspectedTable.getFullyQualifiedTable().toString()));
CommentGenerator commentGenerator = context.getCommentGenerator();
FullyQualifiedJavaType type = new FullyQualifiedJavaType(
introspectedTable.getMyBatis3JavaMapperType());
Interface interfaze = new Interface(type);
interfaze.setVisibility(JavaVisibility.PUBLIC);
commentGenerator.addJavaFileComment(interfaze);
String rootInterface = introspectedTable
.getTableConfigurationProperty(PropertyRegistry.ANY_ROOT_INTERFACE);
if (!stringHasValue(rootInterface)) {
rootInterface = context.getJavaClientGeneratorConfiguration()
.getProperty(PropertyRegistry.ANY_ROOT_INTERFACE);
}
if (stringHasValue(rootInterface)) {
FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(
rootInterface);
interfaze.addSuperInterface(fqjt);
interfaze.addImportedType(fqjt);
}
addCountByExampleMethod(interfaze);
addDeleteByExampleMethod(interfaze);
addDeleteByPrimaryKeyMethod(interfaze);
addInsertMethod(interfaze);
addInsertSelectiveMethod(interfaze);
addSelectByExampleWithBLOBsMethod(interfaze);
addSelectByExampleWithoutBLOBsMethod(interfaze);
addSelectByPrimaryKeyMethod(interfaze);
addUpdateByExampleSelectiveMethod(interfaze);
addUpdateByExampleWithBLOBsMethod(interfaze);
addUpdateByExampleWithoutBLOBsMethod(interfaze);
addUpdateByPrimaryKeySelectiveMethod(interfaze);
addUpdateByPrimaryKeyWithBLOBsMethod(interfaze);
addUpdateByPrimaryKeyWithoutBLOBsMethod(interfaze);
//增加selectAll
addSelectAllMethod(interfaze);
List<CompilationUnit> answer = new ArrayList<CompilationUnit>();
if (context.getPlugins().clientGenerated(interfaze, null,
introspectedTable)) {
answer.add(interfaze);
}
List<CompilationUnit> extraCompilationUnits = getExtraCompilationUnits();
if (extraCompilationUnits != null) {
answer.addAll(extraCompilationUnits);
}
return answer;
}
/**
* 增加eelectAll
* @param interfaze
*/
protected void addSelectAllMethod(Interface interfaze) {
if (introspectedTable.getRules()
.generateSelectByPrimaryKey()) {
AbstractJavaMapperMethodGenerator methodGenerator = new SelectAllMethodGenerator();
initializeAndExecuteGenerator(methodGenerator, interfaze);
}
}
4、配置XML使用上面自定義targetRuntime
inso-generator\src\main\resources\generatorConfig-sys.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="default" targetRuntime="com.xxcomp.core.generator.codegen.InsoIntrospectedTable" defaultModelType="flat">
<plugin type="com.xxcomp.core.generator.plugin.SerializablePlugin"/>
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
<plugin type="com.xxcomp.core.generator.plugin.MapperPlugin">
<property name="targetProject" value="../inso-sys-service/src/main/java"/>
<property name="targetPackage" value="com.xxcomp.dao.generator"/>
<property name="expandTargetPackage" value="com.xxcomp.dao.sys"/>
</plugin>
<commentGenerator>
<property name="suppressDate" value="true" />
</commentGenerator>
<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
connectionURL="jdbc:oracle:thin:@192.168.1.19:1521:EEMS"
userId="TEST" password="TEST">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<javaModelGenerator targetPackage="com.xxcomp.model.generator" targetProject="../inso-sys-api/src/main/java">
<property name="constructorBased" value="false"/>
<property name="useActualColumnNames" value="true" />
<property name="enableSubPackages" value="false"/>
<property name="immutable" value="false"/>
<property name="trimStrings" value="true"/>
<property name="rootClass" value="com.xxcomp.core.base.BaseModel"/>
</javaModelGenerator>
<sqlMapGenerator targetPackage="mappers.generator" targetProject="../inso-sys-service/src/main/resources">
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<javaClientGenerator targetPackage="com.xxcomp.dao.generator" targetProject="../inso-sys-service/src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value=""/>
<property name="methodNameCalculator" value=""/>
<property name="rootInterface" value="com.xxcomp.core.base.BaseMapper"/>
</javaClientGenerator>
<table tableName="SYS_%" catalog="INSO" schema="INSO" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
<!-- 默認為false,如果設置為true,在生成的SQL中,table名字不會加上catalog或schema; -->
<property name="ignoreQualifiersAtRuntime" value="true"/>
</table>
</context>
</generatorConfiguration>
5、pom文件參考
項目原型是ibase4j(http://git.oschina.net/iBase4J/iBase4J),此pom僅供參考一下吧
<?xml version="1.0"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>inso-generator</artifactId>
<name>inso-generator</name>
<url>http://maven.apache.org</url>
<packaging>jar</packaging>
<parent>
<groupId>com.xxcomp</groupId>
<artifactId>inso</artifactId>
<version>0.5.0</version>
</parent>
<!-- 使用不同配置文件生成不同項目的MyBatis文件 -->
<!-- install mybatis-generator:generate -DconfigurationFile=generatorConfig-scheduler.xml -->
<!-- install mybatis-generator:generate -DconfigurationFile=generatorConfig-sys.xml -->
<build>
<finalName>${project.name}</finalName>
<resources>
<resource>
<directory>src/main/java</directory>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
<testIncludes>
<testInclude>none</testInclude>
</testIncludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jdeps-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<goals>
<goal>jdkinternals</goal>
<goal>test-jdkinternals</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
<configurationFile>src/main/resources/${configurationFile}</configurationFile>
</configuration>
<dependencies>
<!--
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
-->
<!-- 導入Oracle數據庫鏈接jar包 -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0</version>
</dependency>
<dependency>
<groupId>com.xxcomp</groupId>
<artifactId>inso-generator</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
通過以上的改造,可以簡單自定義組裝一些原有的方法,生成自己需要的sqlMap,進一步還可以自己編寫具體的方法實現,生成真正自定義的sql。(此步,我沒有去做,太懶了。。)
從沒寫過文章,真不會寫,若看不明白或對你沒幫忙,大俠請自動忽略。
寫一寫才發覺,寫這個有點費時間,雖然我只是貼一下。
2016-09-27 10:31:24