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 同样提供了一级缓 ...
随机推荐
- 用cascade删除有约束的表或记录
删除有约束的表 Drop table TERMPRO_RULE_ROUTE_TYPE cascade constraints:
- Struts2处理逻辑的方式
1.可以统一写一个action 对应方法名处理不同逻辑 2.也可以分别写Action 分别处理不同的逻辑
- Oracle11gr2_ADG管理之switchover实战
. 环境 db_primary db_stanby 备注 db版本 11.2.0.4.0 11.2.0.4.0 os版本 centos 6.4 centos 6.4 db_unique_name ne ...
- MySQL MVCC原理
1 MVCC基本原理 MVCC:多版本并发控制(MVCC,Multiversion Currency Control).一般情况下,事务性储存引擎不是只使用表锁,行加锁的处理数据,而是结合了MVCC机 ...
- Linux系统设置Samba共享笔记
# "不允许一个用户使用一个以上用户名与服务器或共享资源的多重连接" C: 之前曾经与主机成功进行连接,连接断开后未将连接状态清除 $: net use */del /y # &q ...
- 电商模式O2O、C2C、B2B、B2C
电商模式O2O.C2C.B2B.B2C o2o o2o 是 online to offline 分为四种运营模式 1.online to offline 是线上交易到线下消费体验 2.offline ...
- OK6410 linux系统遇到的BUG总结
经过一段时间使用OK6410 256M RAM 2G nand Flash碰见了不少问题. 所以特意开本贴一起交流.大家有什么BUG解决的可以跟上本帖.求助的请另开贴.勿跟本帖.谢谢.请谅解!!! 希 ...
- 爬虫模块之Request
requests Requests唯一一个非转基因的Python HTTP库,人类就可以安全享用. Python标准库中提供了:urllib.urllib2.httplib等模块以供Http请求,但是 ...
- Cfree clion windows c语言 socket 网络编程
server.c #include <stdio.h> #include <winsock2.h> #define SERVER_PORT 5208 //侦听端口 int ma ...
- POJ3017
题意 将一段序列分割为任意段,每一段的连续和不超过M,使得每一段最大值的和最小. 分析 用单调队列进行优化的dp.单调队列可以维护可以影响当前区间的最大值. #include <cstdio&g ...