Mybatis反向工程

前言

Mybatis也有反向工程,用于通过数据库表生成对应的Mapper接口和mapper.xml文件,与Mybatis-plus的代码生成器不同的是,其主要生成的代码在mapper.xml文件中,包含了表的动态增删改查操作。如果不用Mybatis-plus的话用Mybatis反向工程可以生成更为标准的mapper文件。

导入依赖

        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <scope>test</scope>
        </dependency>

由于我们的generator不应打包部署到对应的应用中,所以我们定义scope为test。

编写配置DBGenerator.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" 

[
		<!ENTITY driverClass "com.mysql.cj.jdbc.Driver">
		<!ENTITY connectionURL "jdbc:mysql://127.0.0.1:3306/test">
		<!ENTITY schema "test">
		<!ENTITY userId "test">
		<!ENTITY password "test">

		<!ENTITY beanPath "com.yyoo.mybatis.beans.auto">
		<!ENTITY daoPath "com.yyoo.mybatis.mapper.auto">
		<!ENTITY sqlmapPath "mapper.auto">

		<!ENTITY beanProject "src\main\java">
		<!ENTITY daoProject "src\main\java">
		<!ENTITY sqlmapProject "src\main\resources">

		<!ENTITY daoType "XMLMAPPER">
]>

<generatorConfiguration >

	<!--MyBatis3Simple或MyBatis3-->
  <context id="context1" targetRuntime="MyBatis3">

	  <!-- 指定生成的java文件的编码,没有直接生成到项目时中文可能会乱码 -->
	  <property name="javaFileEncoding" value="UTF-8"/>

  	<!-- plugin -->
  	<plugin type="org.mybatis.generator.plugins.RenameExampleClassPlugin">
  		<property name="searchString" value="Example$" />
		<property name="replaceString" value="Criteria" />
  	</plugin>
  	<!--<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"></plugin>-->
  	<plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>
  	<plugin type="org.mybatis.generator.plugins.ToStringPlugin"></plugin>
	<!-- 解决使用了自定义注释后map.xml文件重复生成的问题-->
	<plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin"></plugin>

	  <!-- 这里的type里写的是你的实现类的类全路径 -->
	  <commentGenerator type="com.yyoo.generator.MyCommentGenerator">
		  <!--<property name="suppressAllComments" value="true" />-->
		  <!--<property name="suppressDate" value="false" />-->
	  </commentGenerator>

	<!-- jdbc-->
	<jdbcConnection driverClass="&driverClass;" connectionURL="&connectionURL;?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8&amp;useSSL=false"
		userId="&userId;" password="&password;" >

		<!-- 针对oracle数据库 -->
		<!--<property name="remarksReporting" value="true"></property>-->

		<!--针对mysql数据库-->
		<property name="useInformationSchema" value="true"></property>

	</jdbcConnection>

	<javaTypeResolver>
		<property name="forceBigDecimals" value="false" />
	</javaTypeResolver>

	<!-- JavaBean -->
	  <!--targetProject属性如果是eclipse就是src就可以了,其他环境下需要是一个实际存在的目录如:D:\generator-->
	<javaModelGenerator targetPackage="&beanPath;" targetProject="&beanProject;">
		<property name="enableSubPackages" value="false" />
		<property name="trimStrings" value="true" />
		<!-- <property name="rootClass" value="apps.myFrame.baseBean.BaseBean" /> -->
	</javaModelGenerator>

	<!-- sqlMap -->
	<sqlMapGenerator targetPackage="&sqlmapPath;" targetProject="&sqlmapProject;">
		<property name="enableSubPackages" value="false" />
	</sqlMapGenerator>

	<!-- dao -->
	<javaClientGenerator targetPackage="&daoPath;" targetProject="&daoProject;" type="&daoType;">
		<property name="enableSubPackages" value="false" />
		<!-- <property name="rootInterface" value="com.yyoo.core.app.BaseDAO" /> -->
	</javaClientGenerator>



	<!-- ******************************************************************************* -->
	  <table schema="&schema;" catalog="&schema;" tableName="t_my_emp" domainObjectName="MyEmpBean"
			 enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
			 enableSelectByExample="false" selectByExampleQueryId="false">
		  <!-- false尝试骆驼大小写返回的名称,true:直接用表中的字段名称 -->
		  <property name="useActualColumnNames" value="false" />
		  <!-- 不将schema或catalog添加到生成的SQL中的表名称 -->
		  <property name="ignoreQualifiersAtRuntime" value="true"/>
	  </table>
	 <!-- ******************************************************************************* -->

</context>
</generatorConfiguration>
<!ENTITY driverClass "com.mysql.cj.jdbc.Driver">:其实就是xml的语法定义,类似于java中定义一个变量。这里的变量名是driverClass,值为com.mysql.cj.jdbc.Driver

commentGenerator 标签中的MyCommentGenerator是我们自定义的生成的类的注释等的配置,可以不用配置,不配置默认使用的是DefaultCommentGenerator。我们自定义配置的话可以继承DefaultCommentGenerator修改我们想要修改的内容。

table标签详解

属性说明
schema& catalog数据库的schema,mysql这里需要设置
tableName数据库表名
domainObjectName生成的JavaBean类名
enable****ByExample是否生成对应的Example操作类,我们的示例全部禁止了

子标签的定义代码中有注释,这里不作说明了。

编写生成代码GeneratorUtil

package com.yyoo.generator;

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;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public abstract class GeneratorUtil {

    /**
     * 默认使用generator.xml文件生成
     */
    public static void generator(){
        generator("generator.xml");
    }

    /**
     * 自定义配置文件生成
     * @param configFile 自定义配置文件的路径
     */
    public static void generator(String configFile){
        try {
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true;
            ConfigurationParser cp = new ConfigurationParser(warnings);
            Configuration config = cp.parseConfiguration(GeneratorUtil.class.getClassLoader().getResourceAsStream(configFile));

            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            myBatisGenerator.generate(null);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (InvalidConfigurationException e) {
            e.printStackTrace();
        } catch (XMLParserException e) {
            e.printStackTrace();
        }
    }

}

测试代码

package com.yyoo.generator;

import org.junit.Test;

public class Main {

    @Test
    public void generator(){

        GeneratorUtil.generator("DBGenerator.xml");

    }

}

本文只是提供一个Mybatis的反向工程的参考代码。内容写得并不详细,这里推荐还是使用Mybatis-plus以及其对应的代码生成器。因为确实简单方便实用。

上一篇:Mybatis-plus进阶之代码生成器
下一篇:待续

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值