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 同样提供了一级缓 ...
随机推荐
- 本人编写的一份前端vue面试题
说明,此题目本人自出,做过本人所在公司的前端面试题,在此共享给大家 1. 如何在vue组件中实现v-model的功能?(只需给出关键代码) 2. 简述你知道的生命周期函数和执行时机 3. 谈谈你对计算 ...
- Python中的闭包与迭代器
前面内容补充 函数名分应用(第一类对象) 函数名的命名规范与变量命名是一样的函数名其实就是变量名 函数名可以作为列表中的元素进行存储 例如: def func1(): pass def func2() ...
- HTML篇
要内容 web标准 浏览器介绍 开发工具介绍 HTML介绍 HTML颜色介绍 HTML规范 HTML结构详解 一.web标准 web准备介绍: w3c:万维网联盟组织,用来制定web标准的机构(组织) ...
- 02-25 类成员的访问权限--internal
C#中还有一种可访问性,就是由关键字internal所确定的“内部”访问性: internal有点像public,外界类也可以直接访问声明为internal的类或类的成员,但这只局限于同一个程序集内部 ...
- mahout in Action2.2-给用户推荐图书(2)-分析对用户推荐书目的结果
2.2.3 Analyzing the output 在之前的程序运行结果中我们得到的结果输出是: RecommendedItem [item:104, value:4.257081] 程序要求选择一 ...
- jQuery.ajax向后台传递数组问题
今天重温了一个问题,jQuery.ajax向后台传递一个数组,而在后台接收不到该值 前台js方法部分代码如下: //创建一个测试数组 var boxIds = new Array(); boxIds. ...
- sublime添加右键菜单
参考:https://www.zhihu.com/question/29662273/answer/45277925 @echo Off :START CLS echo *============== ...
- spring quartz 配置多个定时任务
1.配置文件-quartz-1.7.3jar spring版本为3.1.3jar <?xml version="1.0" encoding="UTF-8&quo ...
- 刷题向》关于第一篇状压DP BZOJ1087 (EASY+)
这是本蒟蒻做的第一篇状压DP,有纪念意义. 这道题题目对状压DP十分友善,算是一道模板题. 分析题目,我们发现可以用0和1代表每一个格子的国王情况, 题目所说国王不能相邻放置,那么首先对于每一行是否合 ...
- Docker学习笔记_安装和使用mysql
一.系统环境和准备 1.宿主机OS:Win10 64位 2.虚拟机OS:Ubuntu18.04 3.操作账号:docker 二.安装 1.搜索mysql镜像:docker search mysql 2 ...