什么是逆向工程
简单的理解,MyBatis逆向工程,就是通过相应插件,自动生成MyBatis数据库连接的一些文件。
mybatis需要编写sql语句,mybatis官方提供逆向工程,可以针对单表自动生成mybatis执行所需要的代码(mapper.java、mapper.xml、pojo…),提高工作效率。
使用步骤
1.创建maven项目
2.在pom.xml中导入依赖 这是基础依赖
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.6</version>
</dependency>
</dependencies>
3.编写逆向工程的文件 [这个地方网上很多 大同小异] 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">
<!-- 配置pojo的序列化 -->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql:///shiro" userId="root"
password="ok">
</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.icanci.pojo"
targetProject=".\src\main\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="cn.icanci.mapper"
targetProject=".\src\main\resources">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="cn.icanci.mapper"
targetProject=".\src\main\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据库表 -->
<table schema="" tableName="permission"/>
<table schema="" tableName="role"/>
<table schema="" tableName="role_permission"/>
<table schema="" tableName="user"/>
<table schema="" tableName="user_role"/>
</context>
</generatorConfiguration>
这是我对用的数据库

我对应的数据库

其中的一张表
4.编写生成CRUD的代码
package cn.icanci.util;
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;
/**
* @Author: icanci
* @ProjectName: mybarisgenerator
* @PackageName: cn.icanci.util
* @Date: Created in 2020/3/10 8:58
* @ClassAction: 测试逆向工程
*/
public class DoIt {
public static void main(String[] args) throws Exception {
try {
DoIt doIt = new DoIt();
doIt.generator();
} catch (Exception e) {
e.printStackTrace();
}
}
public void generator() throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//指定 逆向工程配置文件
File configFile = new File("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);
}
}
5.生成之前 如下

生成之前
6.生成之后 如下

生成之后
7.查看生成的代码 这里没有重写 toString() equals() 和 hashCode() 需要我们自己手动添加 或者使用 Lombok 一键添加 @[工具插件] 简单粗暴节省JavaBean代码插件 Lombok.jar
package cn.icanci.pojo;
import java.io.Serializable;
public class Permission implements Serializable {
private Long id;
private String name;
private String resource;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource == null ? null : resource.trim();
}
}
说明
在创建实例的过程中有一个以Example结尾的类,这个类是专门用来对这个单表来查询的类,就相当于,对该单表的增删改查是脱离sql性质的,直接在service层就可以完成(当然这个sql是逆向已经生过的)
例如:
select id, username, birthday, sex, address from user WHERE ( username = ‘张三’ ) order by username asc
@Test
public void testFindUserByName(){
//通过criteria构造查询条件
UserExample userExample = new UserExample();
userExample.setOrderByClause("username asc"); //asc升序,desc降序排列
userExample.setDistinct(false); //去除重复,true是选择不重复记录,false反之
UserExample.Criteria criteria = userExample.createCriteria(); //构造自定义查询条件
criteria.andUsernameEqualTo("张三");
//自定义查询条件可能返回多条记录,使用List接收
List<User> users = userMapper.selectByExample(userExample);
System.out.println(users);
}
方法说明
mapper 的方法说明
long countByExample(PermissionExample example);
按条件计数
int deleteByExample(PermissionExample example);
按条件删除
int deleteByPrimaryKey(Long id);
按主键删除
int insert(Permission record);
按对象插入
int insertSelective(Permission record);
按条件插入不为null的对象
List<Permission> selectByExample(PermissionExample example);
按条件查询
Permission selectByPrimaryKey(Long id);
按id查询
int updateByExampleSelective(@Param("record") Permission record, @Param("example") PermissionExample example);
按条件更新值不为null的字段
int updateByExample(@Param("record") Permission record, @Param("example") PermissionExample example);
按条件更新
int updateByPrimaryKeySelective(Permission record);
按根据id更新值不为null的字段
int updateByPrimaryKey(Permission record);
按主键更新
example用于添加条件,相当于where后面的部分。
xxxExample example = new xxxExample();
Criteria criteria = example.createCriteria(); //构造自定义查询条件
方法说明:
example.setOrderByClause("字段名 ASC");
添加升序排列条件,DESC为降序
example.setDistinct(false)
去除重复,boolean型,true为选择不重复的记录。
criteria.andXxxIsNull
添加字段xxx为null的条件
criteria.andXxxIsNotNull
添加字段xxx不为null的条件
criteria.andXxxNotEqualTo(value)
添加xxx字段不等于value条件
criteria.andXxxGreaterThan(value)
添加xxx字段大于value条件
criteria.andXxxGreaterThanOrEqualTo(value)
添加xxx字段大于等于value条件
criteria.andXxxLessThan(value)
添加xxx字段小于value条件
criteria.andXxxLessThanOrEqualTo(value)
添加xxx字段小于等于value条件
criteria.andXxxIn(List<?>)
添加xxx字段值在List<?>条件
criteria.andXxxNotIn(List<?>)
添加xxx字段值不在List<?>条件
criteria.andXxxLike("%"+value+"%")
添加xxx字段值为value的模糊查询条件
criteria.andXxxNotLike("%"+value+"%")
添加xxx字段值不为value的模糊查询条件
criteria.andXxxBetween(value1,value2)
添加xxx字段值在value1和value2之间条件
criteria.andXxxNotBetween(value1,value2)
添加xxx字段值不在value1和value2之间条件