The previous article The use of Mybatis reverse engineering mainly talks about the use of mybatis-generator-core-1.3.2.jar. What I want to introduce in this article is to modify the jar package code to achieve the generation of custom templates.
1. From here we can download the source code of mybatis-generator-core-1.3.2.jar project
http://maven.outofmemory.cn/org.mybatis.generator/mybatis-generator-core/1.3.2/
2. Import the existing maven project under eclipse, File->Import
Select the source code location of the project and click finish to complete the import.
The project directory structure is roughly like this.
3. Below I reverse the mapping and xml formats to generate.
4. Start modifying, first explain each directory
The tse package at the bottom is my customized package, which is a main class, testing whether the generated code meets the expected standards.
Since this package was written by foreigners, the generated code style is not much the same as ours. If you want to modify the code format, it is recommended that you read the article on Pineapple Elephant. I won’t talk about the code format here.
http://www.blogjava.net/bolo/archive/2015/03/20/423683.html
First, we first modify the mapping code of the interface file to be generated by the reverse project. By default, there are additions, deletions, modifications and searches. Let's talk about one of the modification methods to update.
For example, I want to have such a method in the generated mapping void update(Map<String, Object> dataMap);
Change the UpdateByPrimaryKeyWithoutBLOBsMethodGenerator class under org.mybatis.generator.codegen.mybatis3.javamapper.elements package, as follows:
/** Copyright 2009 The Apache Software Foundation** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governance permissions and* limitations under the License.*/package org.mybatis.generator.codegen.mybatis3.javamapper.elements;import java.util.Set;import java.util.TreeSet;import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;import org.mybatis.generator.api.dom.java.Interface;import org.mybatis.generator.api.dom.java.JavaVisibility;import org.mybatis.generator.api.dom.java.Method;import org.mybatis.generator.api.dom.java.Parameter;/*** * @author Jeff Butler* */public class UpdateByPrimaryKeyWithoutBLOBsMethodGenerator extendsAbstractJavaMapperMethodGenerator {public UpdateByPrimaryKeyWithoutBLOBsMethodGenerator() {super();}@Overridepublic void addInterfaceElements(Interface interface) {Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();FullyQualifiedJavaType parameterType = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());importedTypes.add(parameterType);//Add a new method Method method = new Method();//Add method modifier PUBLICmethod.setVisability(JavaVisability.PUBLIC);//Set the return value, here I use a custom void, the method without return value getVoidInstance()//FullyQualifiedJavaType class can customize the return value method, you can add it yourself //If you don't want to be so troublesome, you can new FullyQualifiedJavaType("void"), Just write the return type on the constructor method.setReturnType(FullyQualifiedJavaType.getVoidInstance());//Set the method name, you can also go in and see method.setName(introspectedTable.getUpdateByPrimaryKeyStatementId());//Method.addParameter(new Parameter(parameterType, "record")); //$NON-NLS-1$FullyQualifiedJavaType mapType=FullyQualifiedJavaType.getMyMapInstance();//The parameter of the method, here is the dateMap parameter of Map type Parameter = new Parameter(mapType, "dataMap"); method.addParameter(parameter); context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable);addMapperAnnotations(interfaze, method); if (context.getPlugins().clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated(method,interfaze, introspectedTable)) {interfaze.addImportedTypes(importedTypes);interfaze.addMethod(method);}}public void addMapperAnnotations(Interface interface, Method method) {return;}} You can modify it according to the comments.
Next, modify the code in the corresponding XML of mapping. Similarly, here I will only introduce the update method. I believe that after reading it, you can modify other methods by yourself.
Change the UpdateByPrimaryKeyWithoutBLOBsElementGenerator class under org.mybatis.generator.codegen.mybatis3.xmlmapper.elements package, as follows:
/** Copyright 2009 The Apache Software Foundation** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governance permissions and* limitations under the License.*/package org.mybatis.generator.codegen.mybatis3.xmlmapper.elements;import java.util.Iterator;import java.util.List;import org.mybatis.generator.api.IntrospectedColumn;import org.mybatis.generator.api.dom.OutputUtilities;import org.mybatis.generator.api.dom.xml.Attribute;import org.mybatis.generator.api.dom.xml.TextElement;import org.mybatis.generator.api.dom.xml.XmlElement;import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;/*** * @author Jeff Butler* */public class UpdateByPrimaryKeyWithoutBLOBsElementGenerator extendsAbstractXmlElementGenerator {//private boolean isSimple;public UpdateByPrimaryKeyWithoutBLOBsElementGenerator(boolean isSimple) {super();//this.isSimple = isSimple;}@Overridepublic void addElements(XmlElement parentElement) {//update tag (exterior layer of method)XmlElement answer = new XmlElement("update"); //$NON-NLS-1$//Asses of the update tag answer.addAttribute(new Attribute("id", introspectedTable.getUpdateByPrimaryKeyStatementId())); //$NON-NLS-1$answer.addAttribute(new Attribute("parameterType", //$NON-NLS-1$"Map")); //Add the tag into context.getCommentGenerator().addComment(answer);StringBuilder sb = new StringBuilder();sb.append("update"); //$NON-NLS-1$sb.append(introspectedTable.getFullyQualifiedTableNameAtRuntime());//Tag content, that is, text element answer.addElement(new TextElement(sb.toString())); sb.setLength(0);//set tag XmlElement setElement = new XmlElement("set"); //$NON-NLS-1$//Get all fields in the database table List <IntrospectedColumn> cols=introspectedTable.getAllColumns();//Iteration java.util.Iterator<IntrospectedColumn> iter =cols.iterator();while (iter.hasNext()) {//Iterate//Iterate to a certain field IntrospectedColumn introspectedColumn = iter.next();//if tag XmlElement ifElement = new XmlElement("if"); //$NON-NLS-1$// Field name String str=MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn);//If tag add attribute test, the value is field!=null and field!=''ifElement.addAttribute(new Attribute("test",str+" != null and "+str+"!='' "));//if tag content, text element, assign the field the value to be modified sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn));sb.append(" = "); //$NON-NLS-1$sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn)); if (iter.hasNext()) {sb.append(',');}//if tag adds the above text element ifElement.addElement(new TextElement(sb.toString()));if (iter.hasNext()) {sb.setLength(0);OutputUtilities.xmlIndent(sb, 1);}setElement.addElement(ifElement);}//where element (modified field precondition)XmlElement whereElement =new XmlElement("where");for (IntrospectedColumn introspectedColumn : introducedTable.getPrimaryKeyColumns()) {//Transfer the fields in the table to judge sb.setLength(0);sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn));sb.append(" = "); //$NON-NLS-1$sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn));whereElement.addElement(new TextElement(sb.toString()));}//Add the set element and where element in the outermost xml element update element in the method answer.addElement(setElement); answer.addElement(whereElement); if (context.getPlugins().sqlMapUpdateByPrimaryKeyWithoutBLOBsElementGenerated(answer,introspectedTable)) {parentElement.addElement(answer);}}} You can modify other methods according to this update method.
If you want to add a new method, please refer to the following post
http://m.blog.csdn.net/article/details?id=35985705
Next I will verify the modification results
generatorConfig.xml //Configure xml first and place it in the src/main/resources/ directory <?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> <!-- Introduce configuration files--> <!-- Specify data connection driver jar address--> <classPathEntry location="E:/eclipse_workspace/testMybatis/mysql-connector-java-5.1.13-bin.jar" /> <!-- One context for a database --> <context id="infoGuardian" targetRuntime="MyBatis3"> <!-- Comment--> <commentGenerator > <property name="suppressAllComments" value="true"/><!-- Uncomment--> <property name="suppressDate" value="true" /> <!-- Whether to generate comment generation timestamps--> </commentGenerator> <!-- jdbc connection--> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/login?characterEncoding=UTF-8" userId="root" password="root" /> <!-- Type conversion--> <javaTypeResolver> <!-- Whether to use bigDecimal, false can automatically convert the following types (Long, Integer, Short, etc.) --> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- Generate entity class address--> <javaModelGenerator targetPackage="pojo" targetProject="mybatis3" > <!-- Whether to add a new layer of schema under the current path,eg:fase path cn.ffcs.test.domain", true:cn.ffcs.test.domain".[schemaName] --> <property name="enableSubPackages" value="true"/> <!-- Whether to call trim when set for fields of string type --> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- Generate mapxml file --> <sqlMapGenerator targetPackage="mapper" targetProject="mybatis3" > <!-- Whether to add a new layer of schema under the current path, eg:fase path cn.ffcs.test.domain", true:cn.ffcs.test.domain".[schemaName] --> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- Generate mapxml corresponding client, that is, interface dao --> <javaClientGenerator type="XMLMAPPER" targetPackage="mapper" targetProject="mybatis3"> <!-- Whether to add a new layer of schema under the current path, eg:fase path cn.ffcs.test.domain", true:cn.ffcs.test.domain".[schemaName] --> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- Configure table information, no table is generated here, the corresponding table name needs to be changed once --> <table tableName="login" domainObjectName="Login" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> </table> </context> </generatorConfiguration>
StartUp.java//The main program for verification
package tse;import static org.junit.Assert.assertEquals;import java.io.File;import java.util.ArrayList;import java.util.List;import java.util.List;import org.mybatis.generator.api.MyBatisGenerator;import org.mybatis.generator.config.Configuration;import org.mybatis.generator.config.xml.ConfigurationParser;import org.mybatis.generator.internal.DefaultShellCallback;public class StartUp {public static void main(String []args)throws Exception{List<String> warnings = new ArrayList<String>();File configFile=new File(StartUp.class.getResource("/generatorConfig.xml").toURI());ConfigurationParser cp = new ConfigurationParser(warnings);Configuration config = cp.parseConfiguration(configFile);DefaultShellCallback shellCallback = new DefaultShellCallback(true);MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, shellCallback, warnings);myBatisGenerator.generate(null);System.out.println(warnings);}} OK, run StartUp.java
The corresponding file is generated in the target directory according to the configuration of generatorConfig.xml.
OK, the same result as I expected.
5. After the above modifications, we start packaging.
Since it is a maven project, I use maven3.3.9, and you can also use the maven built-in eclipse, but I don't like it anyway.
Below is the pom.xml file code of my maven project
<?xml version="1.0" encoding="UTF-8"?><!--Copyright 2009-2011 The MyBatis TeamLicense under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governance permissions and limitations under the License.--><!--version: $Id: pom.xml 4114 2011-11-27 19:03:32Z simone.tripodi $--><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/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator</artifactId><version>1.3.2</version></parent><artifactId>mybatis-generator-core</artifactId><packaging>jar</packaging><name>MyBatis Generator Core</name><build><!-- this build creates and installs an instrumented JAR filefor use by the systems projects - so we can gather consolidated coverage information--><plugins><!-- <plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-site-plugin</artifactId><executions><execution><phase>prepare-package</phase><goals><goal>site</goal></goals></execution></execution></plugin> --><!-- <plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-source-plugin</artifactId><executions><execution><phase>prepare-package</phase><goals><goal>jar-no-fork</goal></goals></execution></execution></plugin> --><!-- <plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-source-plugin</artifactId><version>2.2.1</version><executions><execution><id>attach-sources</id><goals><goal>jar</goal></goals><configuration><includes><include>**/org/**</include></includes></configuration></execution></plugin> --><!-- <plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-javadoc-plugin</artifactId><executions><execution><phase>prepare-package</phase><goals><goal>jar</goal></goals></execution></executions></plugin> --><plugin><groupId>org.codehaus.mojo</groupId><artifactId>cobertura-maven-plugin</artifactId><executions><execution><id>cobertura-instrument</id><phase>pre-integration-test</phase><goals><goal>instrument</goal></goals></execution></executions> </plugin><!-- <plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-jar-plugin</artifactId><configuration><archive><manifest><mainClass>org.mybatis.generator.api.ShellRunner</mainClass></manifest></archive></configuration><executions><execution><id>cober tura-jar</id><phase>integration-test</phase><goals><goal>jar</goal></goals><configuration><classifier>cobertura</classifier><classesDirectory>${basedir}/target/generated-classes/cobertura</classesDirectory></configuration></execution></executions></plugin> --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-jar-plugin</artifactId><version>2.4</version><executions><execution><id>attach-jar</id><phase>integration-test</phase><goals><goa l>jar</goal></goals></execution></executions><configuration><archive><manifest><addClasspath>true</addClasspath><classpathPrefix></classpathPrefix><mainClass>org.mybatis.generator.api.ShellRunner</main Class></manifest></archive><includes><include>**/org/**</include></includes></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-install-plugin</artifactId><executions><execution><id>cobertura-install</id><phase>integration-test</phase><goals><goal>install</goal></goals><configuration><classifier>cobertura</classifier></configuration></execution></executions> </plugin><!-- <plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-assembly-plugin</artifactId><configuration><descriptors><descriptor>${basedir}/src/main/assembly/src.xml</descriptor></descriptors></configuration> <executions><execution><id>bundle</id><goals><goal>single</goal></goals><phase>package</phase></execution></executions></plugin> --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-assembly-plugin</artifactId><configuration><appendAsemblyId>false</appendAsemblyId><descriptors><descriptor>${basedir}/src/main/assembly/src.xml</descriptor></descriptors></configuration> <executions><execution><id>make-assembly</id><phase>package</phase><goals><goal>single</goal></goals></execution></execution></plugin><plugin><groupId>com.googlecode.maven-gcu-plugin</groupId><artifactId>maven-gcu-plugin</ar tifactId><executions><execution><phase>deploy</phase><goals><goal>upload</goal></goals><configuration><uploads><upload><file>${project.build.directory}/${project.artifactId}-${project.version}-bundle.zip</file><summary>MyBatis Generator ${project.version}</ summary><labels><label>Featured</label><label>Type-Archive</label><label>Product-Generator</label><label>Version-${project.version}</label></labels></upload></uploads></configuration></execution >/executions >/plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-release-plugin</artifactId><configuration><arguments>-Prelease,gupload</arguments></configuration></plugin></plugins></bui ld><reporting><plugins><plugin><groupId>org.codehaus.mojo</groupId><artifactId>jdepend-maven-plugin</artifactId><version>2.0-beta-2</version></plugin><plugin><groupId>org.codehaus.mojo</groupId><artifactId>cobertur a-maven-plugin</artifactId></plugin></plugins></reporting><dependencies><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><scope>provided</scope></dependency><dependency><groupId>org.apache.ant</gro upId><artifactId>ant</artifactId><scope>provided</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency><dependency><groupId>org.hsqldb</groupId><artif actId>hsqldb</artifactId><scope>test</scope></dependency><dependency><groupId>org.apache.maven.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><version>2.12</version></dependency></dependencies><scm> <url>https://mybatis.googlecode.com/svn/sub-projects/generator/tags/mybatis-generator-1.3.2/mybatis-generator-core</url><connection>scm:svn:https://mybatis.googlecode.com/svn/sub-projects/generator/tags/mybatis-gen ether-1.3.2/mybatis-generator-core</connection><developerConnection>scm:svn:https://mybatis.googlecode.com/svn/sub-projects/generator/tags/mybatis-generator-1.3.2/mybatis-generator-core</developerConnection></scm> </project> Then modify the src/main/assembly/src.xml code
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd"><id>bundle</id><formats><format>zip</format></formats><fileSets><fileSet><directory>src/main/resources</directory><outputDirectory>/</outputDirectory><includes><include>genera orConfig.xml</include></includes><excludes><exclude>log4j.properties</exclude><exclude>src.xml</exclude></excludes></fileSet><fileSet><directory>src/main/scripts</directory><outputDirectory>/</outputDirectory><incl ude>run.bat</include></includes></fileSet><fileSet><directory>${project.build.directory}</directory><outputDirectory>/</outputDirectory><includes><include>${project.artifactId}-${project.version}.jar</include></includes></fi leSet><fileSet><directory>${project.build.directory}</directory><outputDirectory>/</outputDirectory><includes><include>${project.artifactId}-${project.version}-sources.jar</include></includes></fileSet></assembly> Next, create a new scripts folder under src/main/, create a new txt text document in the scripts folder, and enter the following code
java -jar mybatis-generator-1.3.2.jar -configfile generatorConfig.xml overwrite
pause
Change the file name to run.bat
At this point, the packaging and configuration are complete.
You can right-click Run as->maven build under the project and enter package in the goal. Or enter the project directory in cmd in the command line and run mvn package. The first time you run it here, you will wait a long time, because maven will download the dependent jar package, please wait patiently.
After packaging, the following structure will be generated in the target directory in the root directory of the project.
From the above figure we can see that the mybatis-generator-core-1.3.2.jar package has been generated. Next we can use it to add generatorConfig.xml to generate the code we want.
If you don't understand anything during the code modification process, please read more of the source code.
OK, show the results
That’s all for this article!
The above is the relevant knowledge about the modification and packaging of the Mybatis reverse engineering jar package introduced to you by the editor. I hope it will be helpful to everyone!