1. 程式人生 > >Mybatis Generator自動生成JavaEntity帶中文註釋和註解[Maven]工程

Mybatis Generator自動生成JavaEntity帶中文註釋和註解[Maven]工程

mybatis-generator是一個很好的資料庫逆向生成Java實體的外掛,但不能新增中文註釋和註解,如果我們想生成下面這樣一個UserEntity,那麼就只能自己動手擴充套件一下mybatis-generator。

package com.domain.entity;

import com.common.entity.BaseEntity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import org.apache.ibatis.type.Alias;

/**
 * user
 */
@Table(name = "user")
@Alias("userEntity")
public class userEntity extends BaseEntity {
    /**
     * 使用者id
     */
    @Id
    @Column(name = "user_id")
    private String userId;

    /**
     * 郵箱(AES)
     */
    @Column(name = "email")
    private String email;


    /**
     * 使用者id
     * @return user_id 使用者id
     */
    public String getUserId() {
        return userId;
    }

    /**
     * 使用者id
     * @param userId 使用者id
     */
    public void setUserId(String userId) {
        this.userId = userId == null ? null : userId.trim();
    }


    /**
     * 郵箱
     * @return email 郵箱
     */
    public String getEmail() {
        return email;
    }

    /**
     * 郵箱
     * @param email 郵箱
     */
    public void setEmail(String email) {
        this.email = email == null ? null : email.trim();
    }

}

我們使用的是mybatis-generator1.3.7版本,以下是pom.xml

<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>
	<groupId>mybatis-generator</groupId>
	<artifactId>mybatis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name />
	<description />
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>5.0.7.RELEASE</version>
		</dependency>
		<!-- Mysql -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.2.7</version>
		</dependency>
		<!-- Mysql 依賴 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.6</version>
		</dependency>
		<!--生成程式碼外掛 -->
		<dependency>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-core</artifactId>
			<version>1.3.7</version>
			<type>jar</type>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
			</plugin>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

配置檔案mybatis-generator-config.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="prod">
		<!-- RowBounds pagination -->
		<plugin type="org.mybatis.generator.plugins.RowBoundsPlugin" />
		<plugin type="org.mybatis.generator.plugins.CaseInsensitiveLikePlugin" />
		<!-- <plugin type="org.mybatis.generator.plugins.SerializablePlugin" /> -->



<!-- 		<commentGenerator>
			<property name="suppressDate" value="true" />
			關閉自動生成的註釋
			<property name="suppressAllComments" value="true" />
		</commentGenerator> -->
		<commentGenerator type="mybatis.MyCommentGenerator">
        </commentGenerator>
        
		<!--資料庫連結地址賬號密碼 -->
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql://192.168.1.30:3306/test?useUnicode=true&characterEncoding=UTF-8"
			userId="123" password="123">
		</jdbcConnection>

		<javaModelGenerator targetPackage="com.domain.entity"
			targetProject="src/main/java">
			<!-- 是否針對string型別的欄位在set的時候進行trim呼叫 -->
			<property name="trimStrings" value="true" />
			<property name="rootClass" value="com.common.entity.BaseEntity" />
		</javaModelGenerator>
		<!-- <sqlMapGenerator targetPackage="mappers" targetProject="src/main/java" 
			/> <javaClientGenerator targetPackage="com.mybatis.mapper" targetProject="src/main/java" 
			type="XMLMAPPER" /> -->


        <!-- type="ANNOTATEDMAPPER",生成基於註解的Mapper介面
                type="MIXEDMAPPER",生成最小的基於註解的Mapper介面
                type="XMLMAPPER",生成SQLMap XML檔案和獨立的Mapper介面 -->
 <!--        <javaClientGenerator type="ANNOTATEDMAPPER" targetPackage="com.fosunlive.amm.domain.entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="ture"/>
        </javaClientGenerator> -->


		<table tableName="user" domainObjectName="userEntity">
			<ignoreColumn column="create_time" delimitedColumnName="" />
			<ignoreColumn column="update_time" delimitedColumnName="" />
			<ignoreColumn column="delflag" delimitedColumnName="" />
		</table>



	</context>
</generatorConfiguration>

關鍵程式碼是這個,我們需要自己寫一個MyCommentGenerator這個類需要繼承DefaultCommentGenerator或者實現CommentGenerator,對原先英文的註釋進行修改,並增加Java註解。

<commentGenerator type="mybatis.MyCommentGenerator">
        </commentGenerator>
MyCommentGenerator程式碼
package mybatis;

import static org.mybatis.generator.internal.util.StringUtility.isTrue;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Set;

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.FullyQualifiedJavaType;
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.java.TopLevelClass;
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.DefaultCommentGenerator;

/**
 * mybatis generator 自定義comment生成器.
 * 
 * @author yihui
 *
 */
public class MyCommentGenerator extends DefaultCommentGenerator {// 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(" */");

		// field.addAnnotation("@Size(min = 0, max = " +
		// introspectedColumn.getLength() + " , message =
		// \"長度必須在{min}和{max}之間\")");
		// field.addAnnotation("@NotNull"); if
		// (introspectedColumn.isStringColumn()) {
		// topLevelClass.addImportedType("javax.validation.constraints.Size");
		// field.addAnnotation("@Size(min = 0, max = " +
		// introspectedColumn.getLength() + " , message =
		// \"長度必須在{min}和{max}之間\")"); }
		List<IntrospectedColumn> primaryKeyColumns = introspectedTable.getPrimaryKeyColumns();
		for (IntrospectedColumn col : primaryKeyColumns) {
			if (col.getActualColumnName().equals(introspectedColumn.getActualColumnName())) {
				field.addAnnotation("@Id");
			}
		}
		field.addAnnotation("@Column(name = \"" + introspectedColumn.getActualColumnName() + "\")");
	}

	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(" */");
	}

	@Deprecated
	public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {

	}

	public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
		topLevelClass.addImportedType("javax.persistence.Column");
		topLevelClass.addImportedType("javax.persistence.Id");
		topLevelClass.addImportedType("javax.persistence.Table");
		topLevelClass.addImportedType("org.apache.ibatis.type.Alias");

		if (suppressAllComments) {
			return;
		}

		StringBuilder sb = new StringBuilder();

		topLevelClass.addJavaDocLine("/**");
		sb.append(" * ");
		sb.append(introspectedTable.getFullyQualifiedTable());
		topLevelClass.addJavaDocLine(sb.toString());

		sb.setLength(0);
		sb.append(" * @author ");
		sb.append(systemPro.getProperty("user.name"));
		sb.append(" ");
		sb.append(currentDateStr);

		// addJavadocTag(innerClass, markAsDoNotDelete);

		topLevelClass.addJavaDocLine(" */");
		topLevelClass.addAnnotation("@Table(name = \"" + introspectedTable.getFullyQualifiedTable() + "\")");
		topLevelClass.addAnnotation("@Alias(\""
				+ toLowerCaseFirstOne(introspectedTable.getTableConfiguration().getDomainObjectName()) + "\")");
	}

	// 首字母轉小寫
	public static String toLowerCaseFirstOne(String s) {
		if (Character.isLowerCase(s.charAt(0)))
			return s;
		else
			return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
	}

	public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable,
			Set<FullyQualifiedJavaType> imports) {
		System.out.println(method.getName());

	}

	public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable,
			IntrospectedColumn introspectedColumn, Set<FullyQualifiedJavaType> imports) {
		System.out.println(method.getName());

	}

	public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable,
			Set<FullyQualifiedJavaType> imports) {
		System.out.println(field.getName());

	}

	public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable,
			IntrospectedColumn introspectedColumn, Set<FullyQualifiedJavaType> imports) {
		System.out.println(field.getName());
		field.addAnnotation("@Column(name = \"" + field.getName() + "\")");
	}

	public void addClassAnnotation(InnerClass innerClass, IntrospectedTable introspectedTable,
			Set<FullyQualifiedJavaType> imports) {
		System.out.println(innerClass);
	}
}

最後一個Main方法可直接執行,生成JavaEntity

package mybatis;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.api.ShellRunner;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import org.springframework.util.ResourceUtils;

public class Generator {
	public static void main(String[] args) {
		args = new String[] { "-configfile", "src\\main\\resources\\mybatis-generator-config.xml", "-overwrite" };
		ShellRunner.main(args);

	}

//      這兩個main方法都可以執行生成JavaEntity不過喜歡上面那個簡潔的方法
//	public static void main(String[] args) throws Exception {
//		File configFile = ResourceUtils.getFile("classpath:mybatis-generator-config.xml");
//		List<String> warnings = new ArrayList<String>();
//		ConfigurationParser cp = new ConfigurationParser(warnings);
//		Configuration config = cp.parseConfiguration(configFile);
//		DefaultShellCallback callback = new DefaultShellCallback(true);
//		MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
//		myBatisGenerator.generate(null);
//
//	}

}

工程下載地址