mybatis学习笔记(五):mybatis 逆向工程
mybatis学习笔记(五):mybatis 逆向工程
在日常开发中,如果数据库中存在多张表,自己手动创建 多个pojo 类和编写 SQL 语法配置文件,未免太过繁琐,mybatis 也提供了一键式生成这些文件的操作,我们称为 mybatis 逆向工程。一般我们在开发中采用由数据库的表生成java代码。
mybatis 逆向工程的下载
贴上官网链接:Mybatis Generator
当然对于 jar 包的下载,我们可以直接使用 maven 导入:
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
运行逆向工程
Mybatis Generator 提供了好几种方式来运行逆向工程:

可以通过 maven 工程,java 程序,eclipse 插件等方式运行,为了后续开发的兼容性问题,在这里我们采用 java 程序通过 xml 方式配置,不用依赖于开发工具。
mybatis 逆向工程实例
在这里我们通过一个具体的例子来演示 mybatis 逆向工程的操作过程。
- 创建一个新的maven工程:mybatis-generator。配置 pom.xml 文件,导入 相关的 jar 包:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.itcast</groupId>
<artifactId>mybatis-generator</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- mysql 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
<!-- mybatis 核心jar包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- mybatis 附加功能包,如日志功能等 -->
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant-launcher</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>5.2</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.5</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.22.0-GA</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.1.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
<scope>test</scope>
</dependency>
<!-- mybatis-generator -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
</dependencies>
</project>
- 在 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="testTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql:///sampledb"
userId="root"
password="">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="cn.itcast.ssm.po"
targetProject="src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="cn.itcast.ssm.mapper"
targetProject="src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="cn.itcast.ssm.mapper"
targetProject="src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据库表 -->
<table tableName="items"></table>
<table tableName="orders"></table>
<table tableName="orderdetail"></table>
<table tableName="user"></table>
<!-- 有些表的字段需要指定java类型
<table schema="" tableName="">
<columnOverride column="" javaType="" />
</table> -->
</context>
</generatorConfiguration>
我们指定需要的文件路径:
javaModelGenerator:生成PO类的位置。
sqlMapGenerator:mapper映射文件生成的位置。
javaClientGenerator:mapper接口生成的位置。
table:指定数据库表。
重要:
需要注意的是这里关于 MySQL 数据库配置这方面,如果按上面的配置文件的话会报如下错误:
Loading class
com.mysql.jdbc.Drive. This is deprecated. The new driver class iscom.mysql.cj.jdbc.Driver. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
其实就是因为我们导入的 mysql-connector包使用了新的驱动,上述的com.mysql.jdbc.Driver已经废弃,建议我们使用 com.mysql.cj.jdbc.Driver,并且还应在连接的URL中需要增加时区信息。另外我们还需要通过设置useSSL=false来显式禁用SSL连接,不然也会报关于 SSL 连接的错误。
改为如下:
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql:///sampledb?serverTimezone=GMT&useSSL=false"
userId="root"
password="">
</jdbcConnection>
- 创建生成程序 GeneratorSqlmap.java ,执行生成程序,生成 mybatis 逆向工程:
package cn.itcast.ssm.generator;
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.File;
import java.util.ArrayList;
import java.util.List;
public class GeneratorSqlmap {
public void generator() throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//指定逆向工程配置文件
File configFile = new File("/Users/weixuqin/IdeaProjects/mybatis-generator/src/main/resources/generatorConfig.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 {
GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
generatorSqlmap.generator();
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 生成后的目录如图所示:

注:
这里我遇到了一个问题,自己有编写日志文件,但是不知道为什么总是无法加载日志信息,报如下信息,查阅相关资料后也没能解决这个问题,以后有时间自己会解决这个问题。

应用 mybatis 逆向工程文件
我们可以复制粘贴逆向工程中的项目到自己另外的项目中使用,不推荐在原有项目中使用 mybatis generator 生成,因为很容易发生命名冲突覆盖的问题。
这里我们将 ItemsMapper.java, ItemsMapper.xml, Items.java, ItemsExample.java 复制粘贴到我们原有项目中,编写测试文件 ItemsMapperTest.java ,查询数据库中 "笔记本" 的记录:
package cn.itcast.ssm.test;
import cn.itcast.ssm.mapper.ItemsMapper;
import cn.itcast.ssm.po.Items;
import cn.itcast.ssm.po.ItemsExample;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class ItemsMapperTest {
private ApplicationContext applicationContext;
private ItemsMapper itemsMapper;
//在 setUp这个方法得到 spring 容器
@Before
public void setUp() throws Exception{
applicationContext = new ClassPathXmlApplicationContext("classpath:config/spring/applicationContext.xml");
itemsMapper = (ItemsMapper) applicationContext.getBean("itemsMapper");
}
@Test
public void testSelectByExample(){
ItemsExample itemsExample = new ItemsExample();
//通过criteria 构造查询条件
ItemsExample.Criteria criteria = itemsExample.createCriteria();
criteria.andNameEqualTo("笔记本");
//可能返回多条记录
List<Items> list = itemsMapper.selectByExample(itemsExample);
System.out.println(list);
}
}
输出结果如下:

这里我刚开始运行的时候始终找不到 selectByExample() 这个方法,其实是因为找不到我的 mapper.xml 映射文件,困惑了好久,发现 mapper.xml 并没有发布到目标文件中,(idea下,eclipse 下并没有这个问题,接口类和映射文件放在同一目录下是允许的)。

所以我们应该将映射文件放在 resourcs 目录下,再在 mybatis 全局配置文件中加载映射文件,再次执行上述测试文件,便不会找不到我们的映射文件了。
<!-- 加载映射文件 -->
<mappers>
<!-- 通过 resource 方法一次加载一个映射文件 -->
<mapper resource="config/sqlmap/ItemsMapper.xml"/>
</mappers>
mybatis学习笔记(五):mybatis 逆向工程的更多相关文章
- Mybatis学习笔记(一) —— mybatis介绍
一.Mybatis介绍 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名 ...
- Mybatis学习笔记(八) —— Mybatis整合spring
一.整合思路 1.SqlSessionFactory对象应该放到spring容器中作为单例存在. 2.传统dao的开发方式中,应该从spring容器中获得sqlsession对象. 3.Mapper代 ...
- MyBatis学习笔记一:MyBatis最简单的环境搭建
MyBatis的最简单环境的搭建,使用xml配置,用来理解后面的复杂配置做基础 1.环境目录树(导入mybatis-3.4.1.jar包即可,这里是为后面的环境最准备使用了web项目,如果只是做 my ...
- Mybatis学习笔记(九) —— Mybatis逆向工程
一.什么是Mybatis逆向工程? 简单的解释就是通过数据库中的单表,自动生成java代码. 我们平时在使用Mabatis框架进行Web应用开发的过程中,需要根据数据库表编写对应的Pojo类和Mapp ...
- MyBatis学习笔记(五)——实现关联表查询
转自孤傲苍狼的博客:http://www.cnblogs.com/xdp-gacl/p/4264440.html 一.一对一关联 1.1.提出需求 根据班级id查询班级信息(带老师的信息) 1.2.创 ...
- Mybatis学习笔记(五) —— Mapper.xml(输入映射和输出映射)
一.parameterType(输入类型) 1.1 传递简单类型 <!-- 根据用户id查询用户 --> <select id="queryUserById" p ...
- 1.2(Mybatis学习笔记)Mybatis核心配置
一.Mybatis核心对象 1.1SqlSeesionFactory SqlSessionFactory主要作用是创建时SqlSession. SqlSessionFactory可通过SqlSessi ...
- Mybatis学习笔记(二) —— mybatis入门程序
一.mybatis下载 mybaits的代码由github.com管理,下载地址:https://github.com/mybatis/mybatis-3/releases 下载完后的目录结构: 二. ...
- MyBatis学习笔记(一)——MyBatis快速入门
转自孤傲苍狼的博客:http://www.cnblogs.com/xdp-gacl/p/4261895.html 一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优 ...
- MyBatis学习笔记(七)——Mybatis缓存
转自孤傲苍狼的博客:http://www.cnblogs.com/xdp-gacl/p/4270403.html 一.MyBatis缓存介绍 正如大多数持久层框架一样,MyBatis 同样提供了一级缓 ...
随机推荐
- 利用JS 在网页上获取并显示当前日期 星期
下边的HTML代码,可以取出日期与星期 <html><body><h1><script language=JavaScript>var d, s = & ...
- Linux进阶路线
初级:熟练使用命令.熟悉Shell编程.能配置简单的服务,清楚各类服务相关的配置文件的位置, 能看懂并可修改系统提供的配置脚本(/etc/*.*)把/etc目录下面常用的配置你都搞懂,把 /bin / ...
- Visual Studio 2005 C# 读写Excel文件
做作业的时候查了一点儿资料, 用的vs2k5 读 excel 发现用起来非常简单...现在编程语言没话说! 项目-添加引用-COM-Microsoft Excel 12.0 Object Librar ...
- 「小程序JAVA实战」 小程序抽离公用方法进行模块化(12)
转自:https://idig8.com/2018/08/09/xiaochengxu-chuji-12/ 小程序的模块化,把砖磊成一个墩子,用的时候把整个墩子移走.js更好的调用,应用更加公用化.源 ...
- chart左侧
左侧单位 Chart1.Axes.Left.Minimum := ; Chart1.Axes.Left.Maximum := Series1.YValues.MaxValue * ; Chart1.A ...
- java8新特性-lambda表达式和stream API的简单使用
一.为什么使用lambda Lambda 是一个 匿名函数,我们可以把 Lambda表达式理解为是 一段可以传递的代码(将代码像数据一样进行传递).可以写出更简洁.更灵活的代码.作为一种更紧凑的代码风 ...
- OK6410 linux系统遇到的BUG总结
经过一段时间使用OK6410 256M RAM 2G nand Flash碰见了不少问题. 所以特意开本贴一起交流.大家有什么BUG解决的可以跟上本帖.求助的请另开贴.勿跟本帖.谢谢.请谅解!!! 希 ...
- 基于C++11的线程池(threadpool),简洁且可以带任意多的参数
咳咳.C++11 加入了线程库,从此告别了标准库不支持并发的历史.然而 c++ 对于多线程的支持还是比较低级,稍微高级一点的用法都需要自己去实现,譬如线程池.信号量等.线程池(thread pool) ...
- 利用Chrome的Performance工具排查页面性能问题(原叫timeline)
当页面中发生卡顿,最先考虑的是swf文件造成的卡顿,经过排查发现不是swf造成的影响,利用Chrome的Performance工具发现页面中的一些元素不断在重新布局,造成潜在的性能瓶颈. 首先在Chr ...
- Linux awk&sed
awk AWK是强大的文本处理工具,擅长对日志文件迚行快速分析. 它丌仅用亍 Linux ,也是任何环境中现有的功能最强大的数据处理引擎之一. 名称得自亍它的发明者 Alfred Aho .Pet ...