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 is com.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&amp;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 逆向工程的更多相关文章

  1. Mybatis学习笔记(一) —— mybatis介绍

    一.Mybatis介绍 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名 ...

  2. Mybatis学习笔记(八) —— Mybatis整合spring

    一.整合思路 1.SqlSessionFactory对象应该放到spring容器中作为单例存在. 2.传统dao的开发方式中,应该从spring容器中获得sqlsession对象. 3.Mapper代 ...

  3. MyBatis学习笔记一:MyBatis最简单的环境搭建

    MyBatis的最简单环境的搭建,使用xml配置,用来理解后面的复杂配置做基础 1.环境目录树(导入mybatis-3.4.1.jar包即可,这里是为后面的环境最准备使用了web项目,如果只是做 my ...

  4. Mybatis学习笔记(九) —— Mybatis逆向工程

    一.什么是Mybatis逆向工程? 简单的解释就是通过数据库中的单表,自动生成java代码. 我们平时在使用Mabatis框架进行Web应用开发的过程中,需要根据数据库表编写对应的Pojo类和Mapp ...

  5. MyBatis学习笔记(五)——实现关联表查询

    转自孤傲苍狼的博客:http://www.cnblogs.com/xdp-gacl/p/4264440.html 一.一对一关联 1.1.提出需求 根据班级id查询班级信息(带老师的信息) 1.2.创 ...

  6. Mybatis学习笔记(五) —— Mapper.xml(输入映射和输出映射)

    一.parameterType(输入类型) 1.1 传递简单类型 <!-- 根据用户id查询用户 --> <select id="queryUserById" p ...

  7. 1.2(Mybatis学习笔记)Mybatis核心配置

    一.Mybatis核心对象 1.1SqlSeesionFactory SqlSessionFactory主要作用是创建时SqlSession. SqlSessionFactory可通过SqlSessi ...

  8. Mybatis学习笔记(二) —— mybatis入门程序

    一.mybatis下载 mybaits的代码由github.com管理,下载地址:https://github.com/mybatis/mybatis-3/releases 下载完后的目录结构: 二. ...

  9. MyBatis学习笔记(一)——MyBatis快速入门

    转自孤傲苍狼的博客:http://www.cnblogs.com/xdp-gacl/p/4261895.html 一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优 ...

  10. MyBatis学习笔记(七)——Mybatis缓存

    转自孤傲苍狼的博客:http://www.cnblogs.com/xdp-gacl/p/4270403.html 一.MyBatis缓存介绍 正如大多数持久层框架一样,MyBatis 同样提供了一级缓 ...

随机推荐

  1. Python内置函数二 (递归函数,匿名函数,二分法)

    匿名函数 lambda() 语法: lambad  参数 : 返回值 def func(a,b): return a * b print(func(2,5)) a = lambda a ,b : a* ...

  2. Linux系统SCSI磁盘扫描机制解析及命令实例(转)

    转载请在文首保留原文出处:EMC中文支持论坛 介绍 Linux系统扫描SCSI磁盘有几种方式?Linux新增LUN之后,能否不重启主机就认出设备?如果安装了PowerPath,动态添加/删除LUN的命 ...

  3. IDE 文件查找快捷键被占

    快捷键 Ctrl+Shift+F 被搜狗输入法抢占了. 打开搜狗输入法里的快捷键设置,去掉,my ide is ok!

  4. MySQL中SQL_CALC_FOUND_ROWS的用法

    1. SQL_CALC_FOUND_ROWS简述 在很多分页的程序中都这样写: #查出符合条件的记录总数 SELECT COUNT(*) from [table] WHERE ......; #查询当 ...

  5. bash&nbsp;shell笔记2&nbsp;结构化命令

    二.使用结构化命令 知识内容: # 改变命令流 # 使用if-then逻辑 # 嵌套if-then # 测试条件 # 高级if-then功能 许多程序在脚本命令之间需要某些逻辑控制流,有些命令允许脚本 ...

  6. android 命名规则

    包名结构: 资源命名方式:

  7. C# 文件打印

    Process pr = new Process();                     pr.StartInfo.FileName = “C:\test.xls”;               ...

  8. java基础之JDBC七:C3P0连接池的使用

    使用C3P0的前提是需要引入jar包 具体使用如下: /** * c3p0的应用 * 前提:引入c3p0的jar包 */ public class Test { public static void ...

  9. 深入剖析SolrCloud(二)

    作者:洞庭散人 出处:http://phinecos.cnblogs.com/ 本博客遵从Creative Commons Attribution 3.0 License,若用于非商业目的,您可以自由 ...

  10. 2014蓝桥杯B组初赛试题《啤酒和饮料》

    题目描述: 啤酒每罐2.3元,饮料每罐1.9元.小明买了若干啤酒和饮料,一共花了82.3元.     我们还知道他买的啤酒比饮料的数量少,请你计算他买了几罐啤酒.     注意:答案是一个整数.请通过 ...