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 同样提供了一级缓 ...
随机推荐
- windows右键打开方式里面添加新的应用程序
1.打开注册表编辑器.打开运行窗口,快捷键,开始+R.输入“regedit”,回车确定. 2.进入注册表编辑器的HKEY_CLASSES_ROOT文件夹下的*子文件夹下的shell文件夹. 3.右键s ...
- Ubuntu下编写C语言程序
新建C文件,新建一个文件用touch,新建文件夹用mkdir. 打开文本编辑器,编辑C文件,命令用gedit xxx.C 编写C程序,Ctrl+S保存 编译运行 1.gcc命令是编译 -o是可选项 是 ...
- PHP 取网页变量
$_POST["test"]; $_GET["test"];isset(); if(isset($_GET["yyuid"]))
- xml和configparser模块
一.xml模块 xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单, 但至今很多传统公司如金融行业的很多系统的接口还主要是xml. xml的格式如下,就是通过 ...
- 【HDU1573】X问题
[题目描述] 求在小于等于N的正整数中有多少个X满足:X mod a[0] = b[0], X mod a[1] = b[1], X mod a[2] = b[2], …, X mod a[i] = ...
- 【bzoj3940】[Usaco2015 Feb]Censoring
[题目描述] FJ把杂志上所有的文章摘抄了下来并把它变成了一个长度不超过10^5的字符串S.他有一个包含n个单词的列表,列表里的n个单词 记为t_1...t_N.他希望从S中删除这些单词. FJ每次 ...
- wangEditor富文本编辑器
设置好了是这样的, 有一个ID问content的编辑框,方便获取,这里的富文本编辑器的版本是2.2 官方文档说3就不支持textarea了 导入一下css 记得css文件夹下应该又3个文件,虽然没有直 ...
- SpringMVC 课程第一天
SpringMVC第一天 框架课程 1. 课程计划 第一天 1.SpringMVC介绍 2.入门程序 3.SpringMVC架构讲解 a) 框架结构 b) 组件说明 4.SpringMVC整合My ...
- Win10 DHCP和Static IP 切换
创建两个.bat文件,分别命名为static.bat和dhcp.bat static.bat文件写入 netsh interface ip set address "Wi-Fi" ...
- 性能优化之_android布局优化
优化布局的的原则就是减少创建的对象的数量,setContentView话费onCreate到onResume中的大概99%的时间1.使用Relativelayout而不是LinearLayout,Li ...