mybatis-generator数据库注释实体类⽣成以及generatorConfig⽂件配置项⽬⾥新建表时model,mapper以及mapper.xml基本都是⽤Mybatis Generator(以下简称为MBG)⾃动⽣成的,但是MBG⾃动⽣成的model的注释实在有点⾮⼈类,⾄少中国⼈是完全接受不了的,在配置中禁⽤掉注释吧,倒是简单了,可是⽣成的model类光秃秃的,啥都没有,字段⽅法没有注释,使⽤很不⽅便,别⼈看也不知道这个字段是啥含义,到最后还是要⾃⼰添加,⼀张表多点⼏⼗个字段,特么添加累死了,不能这么⼲,得想法⼦,百度了⼀下⽹上,基本有两种⽅法,第⼀种,就是直接修改MGB的源代码,第⼆种就是⾃⼰写⼀个类实现CommentGenerator接⼝,先说⾃⼰写⼀个新类实现CommentGenerator接⼝的⽅法来使⾃动⽣成的model类含有中⽂注释吧.⼀:⾸先你得有⼀个maven项⽬,这个我就不多提⼆:通过mybatis generator实现⾃动⽣产model,mapper以及mapper.xml,具体参考 Intellij IDEA 14中使⽤MyBatis-generator ⾃动⽣成MyBatis代码三:通过查看你会发现,注解类是在mybatis-generator-core jar包中 org.mybatis.generator.internal包下的DefaultCommentGenerator类。
那么这⾥有两种⽅法,⼀种是重写DefaultCommentGenerator类,另外⼀种中修改jar包中的源码,但很明显第⼀种⽅法⽐较简单,这⾥也只介绍第⼀种⽅法的写法。
3.1在源代码中新建⼀个类MyCommentGenerator,实现CommentGenerator接⼝,类的代码如下:package org.mybatis.generator;/*** Created by 草帽boy on 2017/2/16.* mybatis generator ⾃定义comment⽣成器.* 基于MBG 1.3.2.* @author ZhangAY 2016-02-19*/import java.text.SimpleDateFormat;import java.util.Date;import java.util.Properties;import mentGenerator;import org.mybatis.generator.api.IntrospectedColumn;import org.mybatis.generator.api.IntrospectedTable;import org.mybatis.generator.api.dom.java.*;import org.mybatis.generator.api.dom.xml.XmlElement;import org.mybatis.generator.config.MergeConstants;import org.mybatis.generator.config.PropertyRegistry;import org.mybatis.generator.internal.util.StringUtility;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 defaultreturn;}/*** 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 defaultreturn;}public void addConfigurationProperties(Properties properties) {this.properties.putAll(properties);suppressDate = StringUtility.isTrue(properties.getProperty(MENT_GENERATOR_SUPPRESS_DATE));suppressAllComments = StringUtility.isTrue(properties.getProperty(MENT_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 addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { }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(""));sb.append(" ");sb.append(currentDateStr);// addJavadocTag(innerClass, markAsDoNotDelete);innerClass.addJavaDocLine(" */");}}3.2.再新建⼀个类StartUp,⽤于运⾏项⽬,(若是集成Eclipse,可直接运⾏操作,查看mybatis与eclipse的集成,这⾥不介绍了)也就是运⾏StartUp类就会直接⽣成model,mapper以及mapper.xml,类的代码如下:package org.mybatis.generator;/*** Created by 草帽boy on 2017/2/16.* 启动⽂件,只需要点击运⾏就⾏*/import java.io.File;import java.io.IOException;import .URISyntaxException;import java.sql.SQLException;import java.util.ArrayList;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.exception.InvalidConfigurationException;import org.mybatis.generator.exception.XMLParserException;import org.mybatis.generator.internal.DefaultShellCallback;public class StartUp {public static void main(String[] args) throws URISyntaxException {try {List<String> warnings = new ArrayList<String>();boolean overwrite = true;//直接获取generatorConfig.xml的⽂件路径根据具体情况查看File configFile = new File("E:\\IDEAWorkPlace\\GraduationDesign\\CourseDesignManageSystem\\20170122\\CourseDesignManage\\src\\main\\resources\\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();}}}3.3 另外需要简单修改⼀下generatorConfig.xml中的注释配置<commentGenerator type="org.mybatis.generator.MyCommentGenerator"><!-- <property name="suppressDate" value="true"/><!– 是否去除⾃动⽣成的注释 true:是: false:否 –><property name="suppressAllComments" value="false"/>--></commentGenerator>commentGenerator 的type是你刚刚重构的MyCommentGenerator类的位置3.4其中我的⽂件结构如下:四:点击运⾏StartUp,你会发现model,mapper以及mapper.xml都已经产⽣,其中实体类的运⾏的结果如下注意:若是出现中⽂乱码,在generatorConfig.xml⽂件中增加以下配置<property name="javaFileEncoding" value="UTF-8"/>1.以下是generatorConfig.xml配置⽂件<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE generatorConfiguration PUBLIC "-////DTD MyBatis Generator Configuration 1.0//EN" "/dtd/mybatis-generator-config_1_0.dtd" > <generatorConfiguration ><!-- 数据库驱动包位置 --><classPathEntrylocation="D:\repository\mysql\mysql-connector-java\5.1.34\mysql-connector-java-5.1.34.jar"/><context id="context1"><property name="javaFileEncoding" value="UTF-8"/><commentGenerator type="com.wareic.utils.MyCommentGenerator"></commentGenerator><!-- <commentGenerator>是否去除⾃动⽣成的注释 true:是: false:否<property name="suppressAllComments" value="true"/></commentGenerator> --><!-- 数据库链接URL、⽤户名、密码 --><jdbcConnection driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://17.16.32.2:3306/db_wareic" userId="root" password="123456"/><!-- ⽣成模型的包名和位置 wareic为项⽬名称 --><javaModelGenerator targetPackage="com.wareic.model" targetProject="wareic/src/main/java"/><!-- ⽣成的映射⽂件报名和位置 --><sqlMapGenerator targetPackage="com.wareic.mapper" targetProject="wareic/src/main/java"/><!-- ⽣成DAO的包名和位置 --><javaClientGenerator targetPackage="com.wareic.mapper" targetProject="wareic/src/main/java" type="XMLMAPPER"/><!-- 要⽣成的那些表(更改tableName 和domainObjectName 就可以了) --><table schema="db_wareic" tableName="t_product" domainObjectName="Product" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"><!-- <columnOverride column="FILMID" property="FILMID" /> --></table></context></generatorConfiguration>2.执⾏startUp类型中的main函数3.MyBatis Generator官⽹:---------------------作者:王卫东来源:CSDN原⽂:https:///wwd0501/article/details/76618363版权声明:本⽂为博主原创⽂章,转载请附上博⽂链接!。