MyBatis Generator原生提供的生成方式targetRuntime有几种,但都不符合项目需求或想自定义自己的方法。
网上的文章也很多:
如:http://generator.sturgeon.mopaas.com/reference/extending.html
这里我说下我的做法:
1、继承IntrospectedTableMyBatis3Impl,重写自己要改写的方法
InsoIntrospectedTable.java
重写calculate
重写createJavaClientGenerator使用自己的JavaMapperGenerator
我的做法比较粗暴,就是注释掉原来的逻辑,自己new自己的替代原来的。
public class InsoIntrospectedTable extends IntrospectedTableMyBatis3Impl { protected void calculate<String> warnings, ProgressCallback progressCallback) {// if (javaClientGenerator == null) {// if (context.getSqlMapGeneratorConfiguration() != null) {// // }// } else {// // } = new Insoprotected AbstractJavaClientGenerator createJavaClientGenerator() { if (context.getJavaClientGeneratorConfiguration() == null) { return null; }// String type = context.getJavaClientGeneratorConfiguration()// .getConfigurationType(); AbstractJavaClientGenerator javaGenerator;// if ("//$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、继承
Inso
public class Insoextends public Insosuper(); } protected = introspectedTable.getFullyQualifiedTable(); progressCallback.startTask(getString( "Progress.12", table.toString())); //$NON-NLS-1$ new //$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( if (introspectedTable.getRules() .generateSelectByPrimaryKey()) { Abstract= new InsoSelectAllElementGenerator(); initializeAndExecuteGenerator(elementGenerator, parentElement); } }}
3、继承JavaMapperGenerator,重写自己要改写的方法
InsoJavaMapperGenerator.java在getCompilationUnits方法中定制自己要的方法,这里我只添加了一个selectAll方法。
注意:这里的项要与上面的
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、配置targetRuntime
inso-generator\src\main\resources\generatorConfig-sys.
- 在targetRuntime中配置全路径类名
- 在table节点,可以配置一些开关,是否生成某些方法,如下,我关掉生成ByExample的方法
- 在table节点里,属性ignoreQualifiersAtRuntime,默认为false,如果设置为true,在生成的SQL中,table名字不会加上catalog或schema,此配置,在Oracle下好用。
<??><!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="> <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仅供参考一下吧
<??><project ="http://maven.apache.org/POM/4.0.0" ="http://www.w3.org/2001/ 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.--> <!-- install mybatis-generator:generate -DconfigurationFile=generatorConfig-sys.--> <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
原标题:定制自己的mybatis生成
关键词:mybatis