Mybatis Generator 的配置和使用

简介

Mybatis Generator 是一个用于 Mybatis 逆向工程的工具。

逆向工程:基于数据库,通过 Mybatis Generator 会生成 4 类文件:实体类,供查询的类,Mapper 接口,和 Mapper 映射文件。

一些常用的自定义配置

不生成 Example 类

Example方法虽然很强大, 但是SQL不易管理,因此不建议使用。

取消 Example 方法的配置:

第一种方法:将 <table>上的 enablexxExample 全部设置为 false

<table tableName="student" domainObjectName="Student"
       enableCountByExample="false" enableUpdateByExample="false"
       enableDeleteByExample="false" enableSelectByExample="false"
       selectByExampleQueryId="false">
	   ...
</table>

第二种方法(推荐):在<context>上设置targetRuntime="MyBatis3Simple"

使用通配符匹配全部的表

<table> 这里用的通配符 % 匹配全部的表。如果不是所有表的配置都一样,可以做针对性的配置。

<table tableName="%">
	<generatedKey column="id" sqlStatement="Mysql"/>
</table>

MSG 使用方法

编写类避免 MybatisGenerator 生成重复代码

OverIsMergeablePlugin.java

import org.mybatis.generator.api.GeneratedXmlFile;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import java.lang.reflect.Field;
import java.util.List;

/**
 * 避免 MybatisGenerator 生成重复代码的插件
 */
public class OverIsMergeablePlugin extends PluginAdapter {
	
	@Override
	public boolean validate(List<String> warnings) {
		return true;
	}

	@Override
	public boolean sqlMapGenerated(GeneratedXmlFile sqlMap, IntrospectedTable introspectedTable) {
		try {
			Field field = sqlMap.getClass().getDeclaredField("isMergeable");
			field.setAccessible(true);
			field.setBoolean(sqlMap, false);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
}

配置 generatorConfig.xml

在 resources 目录下创建 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="DB2Tables" targetRuntime="MyBatis3">

        <!-- 避免生成重复代码的插件 -->
        <plugin type="top.qingrang.util.OverIsMergeablePlugin" />

        <!--是否在代码中显示注释-->
        <commentGenerator>
            <property name="suppressDate" value="true" />
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <!--数据库四要素-->
        <jdbcConnection
                driverClass="com.mysql.jdbc.Driver"
                connectionURL="jdbc:mysql://localhost/mybatis_generator"
                userId="root"
                password="root">
        </jdbcConnection>

        <!-- java 类型处理器
            用于处理 DB 中的类型到 Java 中的类型,默认使用 JavaTypeResolverDefaultImpl;
            注意一点,默认会先尝试使用 Integer,Long,Short 等来对应 DECIMAL 和 NUMERIC 数据类型;
         -->
        <javaTypeResolver>
            <!--
                true:使用 BigDecimal 对应 DECIMAL 和 NUMERIC 数据类型
                false:默认,
                   scale>0;length>18:使用 BigDecimal;
                   scale=0;length[10,18]:使用 Long;
                   scale=0;length[5,9]:使用 Integer;
                   scale=0;length<5:使用 Short;
            -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!--生成 pojo 类存放位置-->
        <javaModelGenerator targetPackage="top.qingrang.pojo" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!--生成 xml 映射文件存放位置-->
        <sqlMapGenerator targetPackage="top.qingrang.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!--生成 mapper 类 存放位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="top.qingrang.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!-- 生成对应表及类名,一张表对应一个 table -->
        <!-- student -->
        <table tableName="student" domainObjectName="Student" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false">
            <property name="my.isgen.usekeys" value="true"/>
            <property name="useActualColumnNames" value="true"/>
            <generatedKey column="id" sqlStatement="JDBC"/>
        </table>
    </context>
</generatorConfiguration>

编写测试运行类,自动生成相关代码

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.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 运行 MybatisGenerator 自动生成相关代码
 */
public class MybatisGenerator {

	public static void main(String[] args) throws Exception {
		String today = "2018-12-14";

		SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
		Date now =sdf.parse(today);
		Date d = new Date();

		if(d.getTime()>now.getTime()+1000*60*60*24){
			System.err.println("——————未成成功运行——————");
			System.err.println("本程序具有破坏作用,应该只运行一次,如果必须要再运行,需要修改today变量为今天,如:" + sdf.format(new Date()));
			return;
		}

		if(false)
			return;
		List<String> warnings = new ArrayList<String>();
		boolean overwrite = true;
		InputStream is= MybatisGenerator.class.getClassLoader().getResource("generatorConfig.xml").openStream();
		ConfigurationParser cp = new ConfigurationParser(warnings);
		Configuration config = cp.parseConfiguration(is);
		is.close();
		DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
		myBatisGenerator.generate(null);

		System.out.println("生成代码成功,只能执行一次,以后执行会覆盖掉 mapper,pojo,xml 等文件上做的修改");
	}
}

自动生成文件介绍与使用

Example 类

Example 类指定如何构建一个动态的 where 子句。

Example 类中包含了一个内部静态类 Criteria,Criteria 包含一个 Cretiron 的集合,每一个 Criteria 对象内包含的 Cretiron 之间是由 AND 连接的, 是逻辑与的关系。

public static class Criteria extends GeneratedCriteria {...}

protected abstract static class GeneratedCriteria {
	protected List<Criterion> criteria;
	...
}

public static class Criterion {...}

// or() 方法,会产生一个新的 Criteria 对象, 添加到 oredCriteria 中, 并返回这个 Criteria 对象。
public Criteria or() {
	Criteria criteria = createCriteriaInternal();
	oredCriteria.add(criteria);
	return criteria;
}

Mapper 类

public interface StudentMapper {
    // 利用 Example 查询
    List<Student> selectByExample(StudentExample example);

    // 根据 pk 查询
    Student selectByPrimaryKey(Integer id);

    // 根据 pk 删除
    int deleteByPrimaryKey(Integer id);

    // 插入,会插入所有字段,包括 null
    int insert(Student record);

    // 插入,不会插入 null 的字段值
    int insertSelective(Student record);

    // 根据 pk 更新所有字段
    int updateByPrimaryKey(Student record);

    // 根据 pk 更新传递过来的不为 null 的 字段
    int updateByPrimaryKeySelective(Student record);
}

利用 Example 实现查询

Example 十分强大,举例了两个常用操作,更多的用法以此类推即可。

/**
 * 利用 Example 实现模糊查询
 * select * from student where name like '%z%'
 */
@Override
public List<Student> selectStudent(String name) {
	StudentExample example = new StudentExample();
	example.createCriteria().andNameLike('%' + name + '%');
	List<Student> studentList = studentMapper.selectByExample(example);
	return studentList;
}

/**
 * 多个 and 和 or 查询
 * select * from student where name like '%z%' and age = 20 or age = 50
 */
@Override
public List<Student> selectStudentList(String name) {
	StudentExample example = new StudentExample();
	// 链式表达
	example.or().andNameLike('%' + name + '%').andAgeEqualTo(20);
	example.or().andAgeEqualTo(50);
	List<Student> studentList = studentMapper.selectByExample(example);
	return studentList;
}

完整 Demo

https://github.com/SSGamble/MybatisGenerator

参考文档

猜你喜欢

转载自blog.csdn.net/SGamble/article/details/85007582