前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >MyBatis Generator( 逆向工程以及源码分析 )

MyBatis Generator( 逆向工程以及源码分析 )

作者头像
时间静止不是简史
发布2020-07-25 17:01:59
8090
发布2020-07-25 17:01:59
举报
文章被收录于专栏:Java探索之路Java探索之路

Mybatis生成器

  • 介绍
  • 使用方式
    • 1 创建Maven项目, 指定为jar类型
    • 2 添加坐标依赖
    • 3 创建配置文件 config.xml
    • 4 创建启动类
    • 5. 查看结果

介绍

  • MyBatis Generator(MBG)是 MyBatis 和 iBATIS 的代码生成工具。它可以为所有 MyBatis 版本以及 iBATIS 版本 2.2.0 及以上自动生成代码。
  • 它会逆向查找一张或多张数据库表的信息,生成操作数据库表所需要的组件。基本上省去了自已手动创建实体类以及配置文件的麻烦。
  • MBG 只是对单表的增删改查(CRUD (Create, Retrieve, Update, Delete))生成了大部分的代码,对于像连接查询或者存储过程之类的,还是需要手动编写 sql 和实体类的。
  • MBG 会生成对应于表结构的 java POJO 类。包括一个支持动态查询、更新和删除的类。
  • MBG 为单表的增删改查生成了配置文件和映射文件。生成的 SQL 语句包括:
代码语言:javascript
复制
insert 
update by primary key 
update by example (使用动态 where 子句) 
delete by primary key delete by example (使用动态 where 子句) 
select by primary key select by example (使用动态 where 子句) 
count by example 返回查询结果的个数

根据表结构的不同,这些语句会有一些变化,比如有的表没有主键,则 MBG 不会生成根据主键更新表的记录的方法。

使用方式

1 创建Maven项目, 指定为jar类型

2 添加坐标依赖

代码语言:javascript
复制
	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
		<dependency>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-core</artifactId>
			<version>1.3.2</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.3.0</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.20</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>2.2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/log4j/log4j -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.12</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.12</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.ow2.asm/asm -->
		<dependency>
			<groupId>org.ow2.asm</groupId>
			<artifactId>asm</artifactId>
			<version>4.2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/cglib/cglib -->
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>3.1</version>
		</dependency>

	</dependencies>

3 创建配置文件 config.xml

至少要指定如下参数:

  • 指定数据库连接的信息:驱动类、连接地址、用户名、密码
  • 指定targetProject:生成POJO类的位置
  • 指定targetProject:mapper映射文件生成的位置
  • targetPackage:mapper接口生成的位置
代码语言:javascript
复制
<?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="testTables" targetRuntime="MyBatis3">
	<!-- 配置生成pojo的序列化的插件,mybatis支持很多插件,这些插件都在 org.mybatis.generator.plugins包下  -->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
    <!-- 配置生成pojo的toString()方法的插件,mybatis支持很多插件,这些插件都在 org.mybatis.generator.plugins包下 -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
        
		<commentGenerator>
			<!-- 是否去除自动生成的注释 true:是 : false:否 -->
			<property name="suppressAllComments" value="true" />
		</commentGenerator>
		<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql://localhost:3306/ego" userId="root"
			password="root">
		</jdbcConnection>
		<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 
			NUMERIC 类型解析为java.math.BigDecimal -->
		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>

		<!-- targetProject:生成POJO类的位置 -->
		<javaModelGenerator targetPackage="ah.szxy.ego.rpc.pojo"
			targetProject=".\src">
			<!-- enableSubPackages:是否让schema作为包的后缀 -->
			<property name="enableSubPackages" value="false" />
			<!-- 从数据库返回的值被清理前后的空格 -->
			<property name="trimStrings" value="true" />
		</javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置 -->
		<sqlMapGenerator targetPackage="ah.szxy.ego.rpc.mapper" 
			targetProject=".\src">
			<!-- enableSubPackages:是否让schema作为包的后缀 -->
			<property name="enableSubPackages" value="false" />
		</sqlMapGenerator>
		<!-- targetPackage:mapper接口生成的位置 -->
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="ah.szxy.ego.rpc.mapper" 
			targetProject=".\src">
			<!-- enableSubPackages:是否让schema作为包的后缀 -->
			<property name="enableSubPackages" value="false" />
		</javaClientGenerator>
		<!-- 指定数据库表 -->
		<table schema="" tableName="tb_content"></table>
		<table schema="" tableName="tb_content_category"></table>
		<table schema="" tableName="tb_item"></table>
		<table schema="" tableName="tb_item_cat"></table>
		<table schema="" tableName="tb_item_desc"></table>
		<table schema="" tableName="tb_item_param"></table>
		<table schema="" tableName="tb_item_param_item"></table>
		<table schema="" tableName="tb_order"></table>
		<table schema="" tableName="tb_order_item"></table>
		<table schema="" tableName="tb_order_shipping"></table>
		<table schema="" tableName="tb_user"></table>

	</context>
</generatorConfiguration>

4 创建启动类

需要指定配置文件所在地址

在这里插入图片描述
在这里插入图片描述
代码语言:javascript
复制
package ah.szxy.mybatis.test;

import java.io.File;
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 MybatisGeneratorTest {
	
	public void generator() throws Exception {

		List<String>warnings = new ArrayList<String>();
		boolean overwrite = true;
		// 指定 逆向工程配置文件/MBG/src/main/resources/config.xml
		File configFile = new File(System.getProperty("user.dir")+"/src/main/resources/config.xml");
		//File configFile = new File(System.getProperty("user.dir")+"/src/config.xml");//普通项目使用
		ConfigurationParser cp = new ConfigurationParser(warnings);
		Configuration config = cp.parseConfiguration(configFile);
		DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
		myBatisGenerator.generate(null);

	}

	public static void main(String[] args) throws Exception {
		try {
			MybatisGeneratorTest generatorSqlmap = new MybatisGeneratorTest();
			generatorSqlmap.generator();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


}

5. 查看结果

  1. 运行完毕后, 控制台如下:
在这里插入图片描述
在这里插入图片描述
  1. 刷新Maven项目后 , 如下图
在这里插入图片描述
在这里插入图片描述
  1. 创建好相对应的包, 将生成的类和配置文件放入到相关的包中. a. 点击实体类, 复制包名 ,在src下创建包名,mapper接口同上
在这里插入图片描述
在这里插入图片描述

b. Mapper的配置文件 ,则可以直接复制到相关项目下 ,但是需要在dao的配置文件注册组件扫描 ,如下面代码和截图

Mapper配置文件所在地址

在这里插入图片描述
在这里插入图片描述

applicationContent-dao.xml 使Mapper生效的配置文件

在这里插入图片描述
在这里插入图片描述

mapper.xml 的组件扫描代码

代码语言:javascript
复制
   <!-- MapperScannerConfigurer -->
   <!-- 设置扫描mybatis接口和映射文件所在的包,生成mapper接口的实现类对象,放到spring的容器中 -->
   <!-- 放到spring中的mapper实现类对象的id是mapper接口类名首字母小写 -->
   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
      <!-- 多个包用逗号或者分号隔开 -->
<!--      <property name="basePackage" value="com.bjsxt.hello,com.bjsxt.ego.mapper"></property> -->
      <property name="basePackage" value="ah.szxy.ego.rpc.mapper"></property>
      <!-- 如果有多个SqlSessionFactory的时候用于指定使用哪个,单个可以不用配置 -->
<!--      <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> -->
   </bean>
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-08-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Mybatis生成器
  • 介绍
  • 使用方式
    • 1 创建Maven项目, 指定为jar类型
      • 2 添加坐标依赖
        • 3 创建配置文件 config.xml
          • 4 创建启动类
            • 5. 查看结果
            相关产品与服务
            数据库
            云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档