Mybatis生成model、dao、mapper文件

整体结构:

Mybatis生成model、dao、mapper文件_第1张图片

pom文件

	
	<dependencies>
		
		<dependency>
			<groupId>org.mybatis.generatorgroupId>
			<artifactId>mybatis-generator-coreartifactId>
			<version>1.3.7version>
		dependency>
		
		<dependency>
			<groupId>org.mybatisgroupId>
			<artifactId>mybatisartifactId>
			<version>3.4.6version>
		dependency>
		
		<dependency>
		    <groupId>mysqlgroupId>
		    <artifactId>mysql-connector-javaartifactId>
		    <version>8.0.16version>
		dependency>
		
	dependencies>

1、junit用于测试使用
2、org.slf4j生成的时候提示slf4j缺失
3、springfox用于model中的swagger注解,非必须

resources:

generator.properties文件

用于数据库连接方面

jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://localhost:3306/myProject?useUnicode=true&characterEncoding=utf-8
jdbc.userId=root
jdbc.password=123456

generatorConfig.xml文件

整体的配置,配置生成文件的目标路径、连接数据库的相关信息等




<generatorConfiguration>
	
	<context id="MySqlContext" targetRuntime="MyBatis3"
		defaultModelType="flat">
		<property name="beginningDelimiter" value="`" />
		<property name="endingDelimiter" value="`" />
		<property name="javaFileEncoding" value="UTF-8" />
		
		<plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
		
		<plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
		
		<plugin
			type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" />
		<commentGenerator type="com.liu.mbg.CommentGenerator">
			
			<property name="suppressAllComments" value="true" />
			<property name="suppressDate" value="true" />
			<property name="addRemarkComments" value="true" />
		commentGenerator>

		<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
			connectionURL="jdbc:mysql://localhost:3306/myProject?useUnicode=true;characterEncoding=utf-8;serverTimezone=Asia/Shanghai"
			userId="root" password="123456">
			
			<property name="nullCatalogMeansCurrent" value="true" />
		jdbcConnection>

		<javaModelGenerator targetPackage="com.liu.model"
			targetProject=".\src\main\java" />

		<sqlMapGenerator targetPackage="com.liu.mapper"
			targetProject=".\src\main\resources" />

		<javaClientGenerator type="XMLMAPPER"
			targetPackage="com.liu.mapper" targetProject=".\src\main\java" />
		
		<table tableName="%">
			<generatedKey column="id" sqlStatement="MySql"
				identity="true" />
		table>
	context>
generatorConfiguration>

java

CommentGenerator.java

swagger注解等方面的配置,非必须,供参考

package com.liu.mbg;

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.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;

import java.util.Properties;

/**
 * 自定义注释生成器
 * Created by macro on 2018/4/26.
 */
public class CommentGenerator extends DefaultCommentGenerator {
    private boolean addRemarkComments = false;
    private static final String EXAMPLE_SUFFIX="Example";
    private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME="io.swagger.annotations.ApiModelProperty";

    /**
     * 设置用户配置的参数
     */
    @Override
    public void addConfigurationProperties(Properties properties) {
        super.addConfigurationProperties(properties);
        this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
    }

    /**
     * 给字段添加注释
     */
    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable,
                                IntrospectedColumn introspectedColumn) {
        String remarks = introspectedColumn.getRemarks();
        //根据参数和备注信息判断是否添加备注信息
        if(addRemarkComments&&StringUtility.stringHasValue(remarks)){
//            addFieldJavaDoc(field, remarks);
            //数据库中特殊字符需要转义
            if(remarks.contains("\"")){
                remarks = remarks.replace("\"","'");
            }
            //给model的字段添加swagger注解
            field.addJavaDocLine("@ApiModelProperty(value = \""+remarks+"\")");
        }
    }

    /**
     * 给model的字段添加注释
     */
    private void addFieldJavaDoc(Field field, String remarks) {
        //文档注释开始
        field.addJavaDocLine("/**");
        //获取数据库字段的备注信息
        String[] remarkLines = remarks.split(System.getProperty("line.separator"));
        for(String remarkLine:remarkLines){
            field.addJavaDocLine(" * "+remarkLine);
        }
        addJavadocTag(field, false);
        field.addJavaDocLine(" */");
    }

    @Override
    public void addJavaFileComment(CompilationUnit compilationUnit) {
        super.addJavaFileComment(compilationUnit);
        //只在model中添加swagger注解类的导入
        if(!compilationUnit.isJavaInterface()&&!compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)){
            compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));
        }
    }
}


Generator.java

用来执行的

package com.liu.mbg;

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;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 用于生产MBG的代码
 * Created by macro on 2018/4/26.
 */
public class Generator {
    public static void main(String[] args) throws Exception {
        //MBG 执行过程中的警告信息
        List<String> warnings = new ArrayList<String>();
        //当生成的代码重复时,覆盖原代码
        boolean overwrite = true;
        String file = "E:\\myProject\\liu\\liu-mbg\\src\\main\\resources\\generatorConfig.xml";
		//读取我们的 MBG 配置文件
//        InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml");
        InputStream is = new FileInputStream(file);
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(is);
        is.close();

        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        //创建 MBG
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        //执行生成代码
        myBatisGenerator.generate(null);
        //输出警告信息
        for (String warning : warnings) {
            System.out.println(warning);
        }
    }
}

结果

Mybatis生成model、dao、mapper文件_第2张图片

完成

你可能感兴趣的:(Mybatis生成model、dao、mapper文件)