欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MyBatis Generator代码生成配置

程序员文章站 2022-04-22 08:24:13
...

官方文档学习:http://www.mybatis.org/generator/configreference/xmlconfig.html

1、generatorConfig.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="test" targetRuntime="MyBatis3">
		<property name="javaFileEncoding" value="UTF-8" />
		<!-- <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"></plugin> -->
		<!-- <plugin type="org.mybatis.generator.plugins.ToStringPlugin"></plugin> -->
		<plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>

		<commentGenerator>
			<property name="suppressDate" value="true" />
			<!-- 是否去除自动生成的注释 true:是 : false:否 -->
			<property name="suppressAllComments" value="false" />
		</commentGenerator>

		<!--数据库链接URL,用户名、密码 -->
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql://localhost:3306/mybatisdb" userId="root"
			password="123456">
		</jdbcConnection>

		<javaTypeResolver>
			<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 
				和 NUMERIC 类型解析为java.math.BigDecimal -->
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>

		<!-- 生成模型的包名和位置 -->
		<javaModelGenerator targetPackage="com.cjh.pojo"
			targetProject="src/main/java">
			<!-- 是否对model添加 构造函数 -->
			<property name="constructorBased" value="true" />
			<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
			<property name="enableSubPackages" value="true" />
			<!-- 是否对类CHAR类型的列的数据进行trim操作 -->
			<property name="trimStrings" value="true" />
		</javaModelGenerator>

		<!-- 生成映射文件的包名和位置 -->
		<sqlMapGenerator targetPackage="com.cjh.mapping"
			targetProject="src/main/java">
			<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
			<property name="enableSubPackages" value="true" />
		</sqlMapGenerator>

		<!-- 生成DAO的包名和位置 -->
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="com.cjh.dao" implementationPackage="com.cjh.dao.impl"
			targetProject="src/main/java">
			<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
			<property name="enableSubPackages" value="true" />
		</javaClientGenerator>

		<!-- 要生成哪些表 -->
		<table tableName="student" domainObjectName="Student"
			enableCountByExample="false" enableUpdateByExample="false"
			enableDeleteByExample="false" enableSelectByExample="false"
			selectByExampleQueryId="false" />

	</context>
</generatorConfiguration>

2、运行,生成代码

(1)如果通过maven方式生成代码,需要在pom配置添加mybatis-generator-maven-plugin插件,参考如下:

<build>
		<plugins>
			<!-- 统一源代码编译输出的JDK版本 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<!-- 打包时跳过单元测试 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.19.1</version>
				<configuration>
					<skipTests>true</skipTests>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.2</version>
				<dependencies>
					<!-- mysql-connector-java 依赖 -->
					<dependency>
						<groupId>mysql</groupId>
						<artifactId>mysql-connector-java</artifactId>
						<version>5.1.47</version>
					</dependency>
					<!-- mybatis-generator-core -->
					<dependency>
						<groupId>org.mybatis.generator</groupId>
						<artifactId>mybatis-generator-core</artifactId>
						<version>1.3.2</version>
					</dependency>

				</dependencies>
				<configuration>
					<!--generatorConfig.xml配置文件的路径 -->
					<configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
					<overwrite>true</overwrite>
				</configuration>
			</plugin>
			<!--mybatis-generator:generate -->
		</plugins>
	</build>

(2)如果通过java代码方式来生成,如下:

  a.还需添加依赖,如下:

<dependencies>
		<!-- mybatis-generator-core -->
		<dependency>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-core</artifactId>
			<version>1.3.2</version>
		</dependency>
		<!-- mysql-connector-java 依赖 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.47</version>
		</dependency>
	</dependencies>

  b.运行代码:


import java.io.InputStream;
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.internal.DefaultShellCallback;

public class Test {
	public static void main(String[] args) {
	    try {
	        List<String> warnings = new ArrayList<String>();
	        boolean overwrite = true;
	        
	        InputStream resourceAsStream = Test.class.getResourceAsStream("generatorConfig.xml");
	        ConfigurationParser cp = new ConfigurationParser(warnings);
	       
	        Configuration config = cp.parseConfiguration(resourceAsStream);
	        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
	        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
	        myBatisGenerator.generate(null);
	        
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}
}

3、自定义生成代码注释

如何实现?

继承org.mybatis.generator.internal.DefaultCommentGenerator类(默认)或实现org.mybatis.generator.api.CommentGenerator接口。重写里面的方法即可。建议参考org.mybatis.generator.internal.DefaultCommentGenerator类,进一步做修改即可,以免出错。

参考(根据需要自己仿DefaultCommentGenerator重写):

package com.cjh.mybatis.generator;

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

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.Method;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.PropertyRegistry;
/**
 * 自定义注释生成器
 * @author 陈嘉豪
 *
 */
public class MyDefaultCommentGenerator implements CommentGenerator {

	private Properties properties;
	private boolean suppressDate;
	private boolean suppressAllComments;

	public MyDefaultCommentGenerator() {
		super();
		properties = new Properties();
		suppressDate = false;
		suppressAllComments = false;
	}
	
	/**
	 * 添加属性注释
	 * @author 陈嘉豪 
	 *(non-Javadoc)
	 * @see org.mybatis.generator.api.CommentGenerator#addFieldComment(org.mybatis.generator.api.dom.java.Field, org.mybatis.generator.api.IntrospectedTable, org.mybatis.generator.api.IntrospectedColumn)
	 */
	@Override
	public void addFieldComment(Field field, IntrospectedTable introspectedTable,
			IntrospectedColumn introspectedColumn) {
		if (suppressAllComments) {
			return;
		}
		field.addJavaDocLine("/**");
		field.addJavaDocLine(" * " + introspectedColumn.getRemarks());
		field.addJavaDocLine(" */");
	}
	@Override
	public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
	}
	@Override
	public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
		if (suppressAllComments) {
			return;
		}
		StringBuilder sb = new StringBuilder();
		innerClass.addJavaDocLine("/**"); 
		sb.append(introspectedTable.getFullyQualifiedTable());
		innerClass.addJavaDocLine(sb.toString());
		innerClass.addJavaDocLine(" */");
	}
	@Override
	public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
		if (suppressAllComments) {
			return;
		}
		StringBuilder sb = new StringBuilder();
		innerClass.addJavaDocLine("/**"); 
		sb.append(introspectedTable.getFullyQualifiedTable());
		innerClass.addJavaDocLine(sb.toString());
		innerClass.addJavaDocLine(" */");
	}
	@Override
	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));
	}
	@Override
	public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
	}
	@Override
	public void addGetterComment(Method method, IntrospectedTable introspectedTable,
			IntrospectedColumn introspectedColumn) {
	}
	@Override
	public void addSetterComment(Method method, IntrospectedTable introspectedTable,
			IntrospectedColumn introspectedColumn) {
	}
	@Override
	public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
	}
	@Override
	public void addJavaFileComment(CompilationUnit compilationUnit) {
	}
	@Override
	public void addComment(XmlElement xmlElement) {
	}
	@Override
	public void addRootComment(XmlElement rootElement) {
	}
	
	protected String getDateString() {
        if (suppressDate) {
            return null;
        } else {
            return new Date().toString();
        }
    }

}

写完之后,还需在配置文件修改如下,指定type,值就是自定义注释生成类的全路径,如下:

<commentGenerator type="com.cjh.mybatis.generator.MyDefaultCommentGenerator">
			<property name="suppressDate" value="true" />
			<!-- 是否去除自动生成的注释 true:是 : false:否 -->
			<property name="suppressAllComments" value="false" />
		</commentGenerator>

4、可能出现的问题

(1)运行异常:Cannot instantiate object of type com.cjh.mybatis.generator.MyDefaultCommentGenerator

解决:将自定义的注释生成器类打包生成jar,然后在pom文件mybatis-generator-maven-plugin插件中添加该依赖。

相关标签: mybatis