什么是逆向工程
簡(jiǎn)單的理解栓霜,MyBatis逆向工程蜕青,就是通過(guò)相應(yīng)插件苟蹈,自動(dòng)生成MyBatis數(shù)據(jù)庫(kù)連接的一些文件。
mybatis需要編寫sql語(yǔ)句右核,mybatis官方提供逆向工程慧脱,可以針對(duì)單表自動(dòng)生成mybatis執(zhí)行所需要的代碼(mapper.java、mapper.xml贺喝、pojo…)菱鸥,提高工作效率。
使用步驟
1.創(chuàng)建maven項(xiàng)目
2.在pom.xml中導(dǎo)入依賴 這是基礎(chǔ)依賴
<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.編寫逆向工程的文件 [這個(gè)地方網(wǎng)上很多 大同小異] 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>
<!-- 是否去除自動(dòng)生成的注釋 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--數(shù)據(jù)庫(kù)連接的信息:驅(qū)動(dòng)類躏鱼、連接地址氮采、用戶名、密碼 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql:///shiro" userId="root"
password="ok">
</jdbcConnection>
<!-- 默認(rèn)false染苛,把JDBC DECIMAL 和 NUMERIC 類型解析為 Integer鹊漠,為 true時(shí)把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" />
<!-- 從數(shù)據(jù)庫(kù)返回的值被清理前后的空格 -->
<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>
<!-- 指定數(shù)據(jù)庫(kù)表 -->
<table schema="" tableName="permission"/>
<table schema="" tableName="role"/>
<table schema="" tableName="role_permission"/>
<table schema="" tableName="user"/>
<table schema="" tableName="user_role"/>
</context>
</generatorConfiguration>
這是我對(duì)用的數(shù)據(jù)庫(kù)
我對(duì)應(yīng)的數(shù)據(jù)庫(kù)
其中的一張表
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: 測(cè)試逆向工程
*/
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.查看生成的代碼 這里沒(méi)有重寫 toString() equals() 和 hashCode() 需要我們自己手動(dòng)添加 或者使用 Lombok 一鍵添加 @[工具插件] 簡(jiǎn)單粗暴節(jié)省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();
}
}
說(shuō)明
在創(chuàng)建實(shí)例的過(guò)程中有一個(gè)以Example結(jié)尾的類主到,這個(gè)類是專門用來(lái)對(duì)這個(gè)單表來(lái)查詢的類,就相當(dāng)于躯概,對(duì)該單表的增刪改查是脫離sql性質(zhì)的登钥,直接在service層就可以完成(當(dāng)然這個(gè)sql是逆向已經(jīng)生過(guò)的)
例如:
select id, username, birthday, sex, address from user WHERE ( username = ‘張三’ ) order by username asc
@Test
public void testFindUserByName(){
//通過(guò)criteria構(gòu)造查詢條件
UserExample userExample = new UserExample();
userExample.setOrderByClause("username asc"); //asc升序,desc降序排列
userExample.setDistinct(false); //去除重復(fù),true是選擇不重復(fù)記錄,false反之
UserExample.Criteria criteria = userExample.createCriteria(); //構(gòu)造自定義查詢條件
criteria.andUsernameEqualTo("張三");
//自定義查詢條件可能返回多條記錄,使用List接收
List<User> users = userMapper.selectByExample(userExample);
System.out.println(users);
}
方法說(shuō)明
mapper 的方法說(shuō)明
long countByExample(PermissionExample example);
按條件計(jì)數(shù)
int deleteByExample(PermissionExample example);
按條件刪除
int deleteByPrimaryKey(Long id);
按主鍵刪除
int insert(Permission record);
按對(duì)象插入
int insertSelective(Permission record);
按條件插入不為null的對(duì)象
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);
按根據(jù)id更新值不為null的字段
int updateByPrimaryKey(Permission record);
按主鍵更新
example用于添加條件,相當(dāng)于where后面的部分娶靡。
xxxExample example = new xxxExample();
Criteria criteria = example.createCriteria(); //構(gòu)造自定義查詢條件
方法說(shuō)明:
example.setOrderByClause("字段名 ASC");
添加升序排列條件牧牢,DESC為降序
example.setDistinct(false)
去除重復(fù),boolean型姿锭,true為選擇不重復(fù)的記錄塔鳍。
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之間條件