mybatis generator How to Customize Annotation Generation

  • 2021-11-10 09:49:20
  • OfStack

Directory preface body 1. Implement CommentGenerator interface 2. Configure generator. xml3. Run method 1. java method (recommended by individuals) method 2. maven method 4. Possible problems 4.1 Prompt can't find MyCommentGenerator4.2 Can't get field annotation 4.3 Generated javabean field annotation Chinese garbled code

Preface

This article was written in February 2016 and is based on mybatis-generator 1.3. 2.

At present, the official version of mybatis-generator has been updated to version 1.3. 5, and this article is also applicable to 1.3. 3 ~ 1.3. 5. However, some new methods in CommentGenerator interface need additional implementation, which should be noted when using the code examples provided in this article. After all, this article is the interface of 1.3. 2 implementation.

In theory, even if mybatis-generator is updated again, as long as the interface remains unchanged and the architecture remains unchanged, this article is still applicable. After all, the principle is the same.

It should be noted that addRemarkComments attribute has been added under commentGenerator tag since version 1.3. 3 (see commentGenerator for details), which can replace some functions in this article to some extent. You can try the effect before deciding whether to realize annotation generation by yourself.

-- 2016.08.27

Completed 1 detail. Added new solutions to 4.1 issues. Thanks for the comments @ Armeng.

-- 2016.09.28

The operation method provided in the previous step 3 is only maven mode, while java mode is placed in 4.1, which causes inconvenience to many readers. It is mainly adjusted (after adjustment, 3.1 is java mode, 3.2 is maven mode), and the example code of java mode is improved incidentally.

-- 2018.12.26

Text

The code comments automatically generated by mybatis-generator are very anti-human. Usually, when we use them, we close the comments according to the following settings:


<commentGenerator>
 <!--   Turn off automatically generated comments   -->
 <property name="suppressAllComments" value="true" />
</commentGenerator>

However, there is such a paragraph in commentGenerator1 section of mybatis-generator official document:

The default implementation is org.mybatis.generator.internal.DefaultCommentGenerator. The default implementation is designed for extensibility if you only want to modify certain behaviors.

Since it is extensible, what should be done? It is also stated in the document that you only need to implement the org. mybatis. generator. api. CommentGenerator interface with a constructor of public, and then add the attribute type to commentGenerator, and set its value to the full path of the implementation class.

Well, that's what the document says. Let's see how to do it.

In advance, I stated that I used Eclipse+Maven to build.

1. Implement the CommentGenerator interface

Of course, first of all, you should have the jar package mybatis-generator-core in your project. The relevant pom is as follows:


<dependency>
 <groupId>org.mybatis.generator</groupId>
 <artifactId>mybatis-generator-core</artifactId>
 <!--  Pay attention to the version . The sample code uses the 1.3.2. Adopt a higher version to realize the newly added interface by yourself . -->
 <version>1.3.2</version>
</dependency>

Text, the implementation of CommentGenerator interface, of course, inherit the default implementation of DefaultCommentGenerator also line. And then implement or rewrite their own needs of the method. The process is best to refer to the DefaultCommentGenerator inside the code to do.

There is nothing more to say, the following is my realization.


import static org.mybatis.generator.internal.util.StringUtility.isTrue;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.api.dom.java.InnerEnum;
import org.mybatis.generator.api.dom.java.JavaElement;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.MergeConstants;
import org.mybatis.generator.config.PropertyRegistry;
/**
 * mybatis generator  Customize comment Generator .
 *  Based on MBG 1.3.2.
 * @author ZhangAY 2016-02-19
 *
 */
public class MyCommentGenerator implements CommentGenerator {
private Properties properties;
private Properties systemPro;
private boolean suppressDate;
private boolean suppressAllComments;
private String currentDateStr;
public MyCommentGenerator() {
	super();
	properties = new Properties();
	systemPro = System.getProperties();
	suppressDate = false;
	suppressAllComments = false;
	currentDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
}
public void addJavaFileComment(CompilationUnit compilationUnit) {
	// add no file level comments by default
	return;
}
/**
 * Adds a suitable comment to warn users that the element was generated, and
 * when it was generated.
 */
public void addComment(XmlElement xmlElement) {
	return;
}
public void addRootComment(XmlElement rootElement) {
	// add no document level comments by default
	return;
}
public void addConfigurationProperties(Properties properties) {
	this.properties.putAll(properties);
	suppressDate = isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE));
	suppressAllComments = isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS));
}
/**
 * This method adds the custom javadoc tag for. You may do nothing if you do
 * not wish to include the Javadoc tag - however, if you do not include the
 * Javadoc tag then the Java merge capability of the eclipse plugin will
 * break.
 * 
 * @param javaElement
 *            the java element
 */
protected void addJavadocTag(JavaElement javaElement, boolean markAsDoNotDelete) {
	javaElement.addJavaDocLine(" *");
	StringBuilder sb = new StringBuilder();
	sb.append(" * ");
	sb.append(MergeConstants.NEW_ELEMENT_TAG);
	if (markAsDoNotDelete) {
		sb.append(" do_not_delete_during_merge");
	}
	String s = getDateString();
	if (s != null) {
		sb.append(' ');
		sb.append(s);
	}
	javaElement.addJavaDocLine(sb.toString());
}
/**
 * This method returns a formated date string to include in the Javadoc tag
 * and XML comments. You may return null if you do not want the date in
 * these documentation elements.
 * 
 * @return a string representing the current timestamp, or null
 */
protected String getDateString() {
	String result = null;
	if (!suppressDate) {
		result = currentDateStr;
	}
	return result;
}
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
	if (suppressAllComments) {
		return;
	}
	StringBuilder sb = new StringBuilder();
	innerClass.addJavaDocLine("/**");
	sb.append(" * ");
	sb.append(introspectedTable.getFullyQualifiedTable());
	sb.append(" ");
	sb.append(getDateString());
	innerClass.addJavaDocLine(sb.toString());
	innerClass.addJavaDocLine(" */");
}
public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
	if (suppressAllComments) {
		return;
	}
	
	StringBuilder sb = new StringBuilder();
	
	innerEnum.addJavaDocLine("/**");
	//		addJavadocTag(innerEnum, false);
	sb.append(" * ");
	sb.append(introspectedTable.getFullyQualifiedTable());
	innerEnum.addJavaDocLine(sb.toString());
	innerEnum.addJavaDocLine(" */");
}
public void addFieldComment(Field field, IntrospectedTable introspectedTable,
		IntrospectedColumn introspectedColumn) {
	if (suppressAllComments) {
		return;
	}
	StringBuilder sb = new StringBuilder();
	field.addJavaDocLine("/**");
	sb.append(" * ");
	sb.append(introspectedColumn.getRemarks());
	field.addJavaDocLine(sb.toString());
	//		addJavadocTag(field, false);
	field.addJavaDocLine(" */");
}
public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
	if (suppressAllComments) {
		return;
	}
	
	StringBuilder sb = new StringBuilder();
	
	field.addJavaDocLine("/**");
	sb.append(" * ");
	sb.append(introspectedTable.getFullyQualifiedTable());
	field.addJavaDocLine(sb.toString());
	field.addJavaDocLine(" */");
}
public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
	if (suppressAllComments) {
		return;
	}
	//		method.addJavaDocLine("/**");
	//		addJavadocTag(method, false);
	//		method.addJavaDocLine(" */");
}
public void addGetterComment(Method method, IntrospectedTable introspectedTable,
		IntrospectedColumn introspectedColumn) {
	if (suppressAllComments) {
		return;
	}
	method.addJavaDocLine("/**");
	StringBuilder sb = new StringBuilder();
	sb.append(" * ");
	sb.append(introspectedColumn.getRemarks());
	method.addJavaDocLine(sb.toString());
	
	sb.setLength(0);
	sb.append(" * @return ");
	sb.append(introspectedColumn.getActualColumnName());
	sb.append(" ");
	sb.append(introspectedColumn.getRemarks());
	method.addJavaDocLine(sb.toString());
	//		addJavadocTag(method, false);
	method.addJavaDocLine(" */");
}
public void addSetterComment(Method method, IntrospectedTable introspectedTable,
		IntrospectedColumn introspectedColumn) {
	if (suppressAllComments) {
		return;
	}
	method.addJavaDocLine("/**");
	StringBuilder sb = new StringBuilder();
	sb.append(" * ");
	sb.append(introspectedColumn.getRemarks());
	method.addJavaDocLine(sb.toString());
	Parameter parm = method.getParameters().get(0);
	sb.setLength(0);
	sb.append(" * @param ");
	sb.append(parm.getName());
	sb.append(" ");
	sb.append(introspectedColumn.getRemarks());
	method.addJavaDocLine(sb.toString());
	//		addJavadocTag(method, false);
	method.addJavaDocLine(" */");
}
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
	if (suppressAllComments) {
		return;
	}
	StringBuilder sb = new StringBuilder();
	innerClass.addJavaDocLine("/**");
	sb.append(" * ");
	sb.append(introspectedTable.getFullyQualifiedTable());
	innerClass.addJavaDocLine(sb.toString());
	
	sb.setLength(0);
	sb.append(" * @author ");
	sb.append(systemPro.getProperty("user.name"));
	sb.append(" ");
	sb.append(currentDateStr);
	//		addJavadocTag(innerClass, markAsDoNotDelete);
	innerClass.addJavaDocLine(" */");
}

2. Configure generator. xml

Configure as follows. Note that the value of type is the full path of the MyCommentGenerator class.


<commentGenerator type="MyCommentGenerator">
</commentGenerator>

Step 3 Run

MBG (the abbreviation of MyBatis Generator) supports a variety of operation modes, only two of which are listed in this article (java mode and maven mode)

If you need to run it by command line or other means, refer to the official website documentation:

Method 1. java (recommended by individuals)

Directly to main method to run, mainly save trouble not easy to make mistakes. Code as follows:


public static void main(String[] args) {
 //  Exception information in execution is saved in the warnings Medium  
 List<String> warnings = new ArrayList<String>();
    try {
        // true: The generated file overwrites the previous 
        boolean overwrite = true;
        //  Read configuration , Structure  Configuration  Object .  
        //  If you don't want to use a configuration file , You can also come directly  new Configuration(), Then assign a value to the corresponding attribute .
        File configFile = new File("generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (InvalidConfigurationException e) {
        e.printStackTrace();
    } catch (XMLParserException e) {
        e.printStackTrace();
    }
    
    for (String warning : warnings){
        System.out.println(warning);
    }
}

Method 2. maven mode

Package the MyCommentGenerator class to generate jar and add it to the maven library, similar to this:


 <dependency>
  <groupId>com.saddestmoon</groupId>
  <artifactId>MyCommentGenerator</artifactId>
  <version>0.1.SNAPSHOT</version>
 </dependency>

The mybatis-generator-maven-plugin plug-in adds related dependencies:


 <plugin>
  <groupId>org.mybatis.generator</groupId>
  <artifactId>mybatis-generator-maven-plugin</artifactId>
  <version>1.3.2</version>
  <dependencies>
   <dependency>
    <groupId>com.saddestmoon</groupId>
    <artifactId>MyCommentGenerator</artifactId>
    <version>0.1.SNAPSHOT</version>
   </dependency>
  </dependencies>
 </plugin>

Then right-click the project, run as- > maven, fill in relevant parameters and run mybatis generator.

Finally, the automatically generated code should be similar to the following:


 /**
 *  File code 
 */
private String fileCd;
/**
 *  File code 
 * @return FILE_CD  File code 
 */
public String getFileCd() {
    return fileCd;
}
/**
 *  File code 
 * @param fileCd  File code 
 */
public void setFileCd(String fileCd) {
    this.fileCd = fileCd;
}

4. Possible problems

In most cases, step 3 is the end. Below, they are all stepping pits.

4.1 Prompt not found MyCommentGenerator

This 1 is usually an error that occurs when running MBG using the Maven command.

The reason is that mybatis-generator-core and MyCommentGenerator are not under the same ClassPath. The solution is as follows:

Refer to section 3.2, 1 Be sure to package and generate jar, and then add the dependencies in the pom file mybatis-generator-maven-plugin plug-in.

Running MBG in Java mode (see 3.1) avoids this problem and does not need to be packaged as jar:

4.2 Unable to get field comments

Yes, that is, introspectedColumn. getRemarks () can't get the field comments, and null is displayed where the field comments should be displayed in the generated javabean.

In the configuration file, we set the < jdbcConnection > Make the following modifications:


<jdbcConnection driverClass="${driver}"
 connectionURL="{url}" userId="${username}" password="${password}">
 <!--  Aim at oracle Database  -->
 <property name="remarksReporting" value="true"></property>
 <!--  Aim at mysql Database  -->
    <property name="useInformationSchema" value="true"></property>
</jdbcConnection>

Problem solving

See another article Mybatis Generator for a detailed solution to this problem. If you are not using Oracle or Mysql, you'd better look at it.

4.3 Field annotation in generated javabean in Chinese garbled code

This requires manually setting the encoding of the generated file.

In the official document < context > Section 1 < Property > There are relevant instructions, as follows.

javaFileEncoding Use this property to specify an encoding to use when working with Java files. Newly generated Java files will be written to the file system in this encoding, and existing Java files will be read with this encoding when performing a merge. If not specified, then the platform default encoding will be used.

So in the configuration file < context > Add the following sub-elements to:


<property name="javaFileEncoding" value="UTF-8"/>

Note: < context > Under the child elements must be in accordance with the prescribed order, otherwise the operation will report errors!


Related articles: