MyBatis的逆向工程
正向工程:先创建Java实体类,由框架负责根据实例类生成数据库表。Hibernate是支持正向工程的。
逆向工程:先创建数据库表,由框架负责根据数据库表,正向生成如下资源
- Java实体类
- Mapper接口
- Mapper映射文件
创建逆向工程的步骤
- 添加依赖和插件
pom.xml
<?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>com.bijing.mybatis</groupId>
<artifactId>mybatis_dynamicSQL</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 打包方式jar-->
<packaging>jar</packaging>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<!--MyBatis核心-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.11</version>
</dependency>
<!--MYSQL驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<!-- log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--junit测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<!-- 控制maven在构建过程中的相关配置-->
<build>
<!-- 构建过程中用到的插件-->
<plugins>
<!-- 具体插件,逆向工程的操作是以构建过程中的插件形式出现的-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.1</version>
<!-- 插件的依赖-->
<dependencies>
<!-- 逆向工程的核心依赖-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.1</version>
</dependency>
<!-- MYSQL驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
- 创建MyBatis核心配置文件
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- MyBatis核心配置文件中的标签必须按照指定的顺序配置:
properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,
objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?
-->
<!-- 引入properties文件,此后就可以在当前文件中使用的方式访问value-->
<properties resource="jdbc.properties">
</properties>
<settings>
<!-- 将下划线映射为驼峰-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!-- typeAliases:设置类型别名,即为某个具体的数据类型设置一个别名
在MyBatis的范围中,就可以使用别名来表示一个具体的类型
-->
<typeAliases>
<package name="com.bijing.mybatis.pojo"/>
</typeAliases>
<!-- 配置连接数据库的环境
default:设置默认使用的环境id
-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 引入mybatis的映射文件-->
<mappers>
<package name="com.bijing.mybatis.mapper"/>
</mappers>
</configuration>
- 创建逆向工程的配置文件
在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>
<!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包 -->
<!-- <classPathEntry-->
<!-- location="/Users/bijing/Documents/software/java/各种jar包/mysql-connector-java-8.0.29"></classPathEntry>-->
<!-- targetRuntime:执行生成的逆向工程的版本
MyBatis3Simple:生成基本的CRUD
MyBatis3:生成带条件的CRUD
-->
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 实体类生成序列化属性-->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<!-- 实体类重写HashCode()和equals()-->
<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
<!-- 实体类重写toString() -->
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<commentGenerator>
<!-- 是否去除自动生成的注释 -->
<property name="suppressAllComments" value="true"/>
<!-- 生成注释是否带时间戳-->
<property name="suppressDate" value="true"/>
<!-- 生成的Java文件的编码格式 -->
<property name="javaFileEncoding" value="utf-8"/>
<!-- 格式化java代码-->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- 格式化XML代码-->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
</commentGenerator>
<!-- 数据库连接驱动类,URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC"
userId="root" password="root1234">
</jdbcConnection>
<!-- java类型处理器:处理DB中的类型到Java中的类型 -->
<javaTypeResolver type="org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl">
<!-- 是否有效识别DB中的BigDecimal类型 -->
<property name="forceBigDecimals" value="true"/>
</javaTypeResolver>
<!-- 生成实体类 -->
<javaModelGenerator targetPackage="com.bijing.mybatis.pojo"
targetProject="./src/main/java">
<!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false -->
<property name="enableSubPackages" value="true"/>
<!-- 设置是否在getter方法中,对String类型字段调用trim()方法-->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成xml映射文件:包名(targetPackage)、位置(targetProject) -->
<sqlMapGenerator targetPackage="com.bijing.mybatis.mapper" targetProject="./src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO接口:包名(targetPackage)、位置(targetProject) -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.bijing.mybatis.mapper"
targetProject="./src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表:tableName - 数据库中的表名或视图名,domainObjectName - 实体类名 -->
<table tableName="t_emp" domainObjectName="Emp">
</table>
<table tableName="t_dept" domainObjectName="Dept"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
-
执行MBG插件的generate目标
-
效果
自动生成了实例类,映射文件,DAO接口
QBC查询
在generatorConfig.xml中如果 targetRuntime=“MyBatis3”,会生成实体类和它的Example
<!-- targetRuntime:执行生成的逆向工程的版本
MyBatis3Simple:生成基本的CRUD
MyBatis3:生成带条件的CRUD
-->
<context id="DB2Tables" targetRuntime="MyBatis3">
EmpExample.java
package com.bijing.mybatis.pojo;
import java.util.ArrayList;
import java.util.List;
public class EmpExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public EmpExample() {
oredCriteria = new ArrayList<>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andEmpIdIsNull() {
addCriterion("emp_id is null");
return (Criteria) this;
}
public Criteria andEmpIdIsNotNull() {
addCriterion("emp_id is not null");
return (Criteria) this;
}
public Criteria andEmpIdEqualTo(Integer value) {
addCriterion("emp_id =", value, "empId");
return (Criteria) this;
}
public Criteria andEmpIdNotEqualTo(Integer value) {
addCriterion("emp_id <>", value, "empId");
return (Criteria) this;
}
public Criteria andEmpIdGreaterThan(Integer value) {
addCriterion("emp_id >", value, "empId");
return (Criteria) this;
}
public Criteria andEmpIdGreaterThanOrEqualTo(Integer value) {
addCriterion("emp_id >=", value, "empId");
return (Criteria) this;
}
public Criteria andEmpIdLessThan(Integer value) {
addCriterion("emp_id <", value, "empId");
return (Criteria) this;
}
public Criteria andEmpIdLessThanOrEqualTo(Integer value) {
addCriterion("emp_id <=", value, "empId");
return (Criteria) this;
}
public Criteria andEmpIdIn(List<Integer> values) {
addCriterion("emp_id in", values, "empId");
return (Criteria) this;
}
public Criteria andEmpIdNotIn(List<Integer> values) {
addCriterion("emp_id not in", values, "empId");
return (Criteria) this;
}
public Criteria andEmpIdBetween(Integer value1, Integer value2) {
addCriterion("emp_id between", value1, value2, "empId");
return (Criteria) this;
}
public Criteria andEmpIdNotBetween(Integer value1, Integer value2) {
addCriterion("emp_id not between", value1, value2, "empId");
return (Criteria) this;
}
public Criteria andEmpNameIsNull() {
addCriterion("emp_name is null");
return (Criteria) this;
}
public Criteria andEmpNameIsNotNull() {
addCriterion("emp_name is not null");
return (Criteria) this;
}
public Criteria andEmpNameEqualTo(String value) {
addCriterion("emp_name =", value, "empName");
return (Criteria) this;
}
public Criteria andEmpNameNotEqualTo(String value) {
addCriterion("emp_name <>", value, "empName");
return (Criteria) this;
}
public Criteria andEmpNameGreaterThan(String value) {
addCriterion("emp_name >", value, "empName");
return (Criteria) this;
}
public Criteria andEmpNameGreaterThanOrEqualTo(String value) {
addCriterion("emp_name >=", value, "empName");
return (Criteria) this;
}
public Criteria andEmpNameLessThan(String value) {
addCriterion("emp_name <", value, "empName");
return (Criteria) this;
}
public Criteria andEmpNameLessThanOrEqualTo(String value) {
addCriterion("emp_name <=", value, "empName");
return (Criteria) this;
}
public Criteria andEmpNameLike(String value) {
addCriterion("emp_name like", value, "empName");
return (Criteria) this;
}
public Criteria andEmpNameNotLike(String value) {
addCriterion("emp_name not like", value, "empName");
return (Criteria) this;
}
public Criteria andEmpNameIn(List<String> values) {
addCriterion("emp_name in", values, "empName");
return (Criteria) this;
}
public Criteria andEmpNameNotIn(List<String> values) {
addCriterion("emp_name not in", values, "empName");
return (Criteria) this;
}
public Criteria andEmpNameBetween(String value1, String value2) {
addCriterion("emp_name between", value1, value2, "empName");
return (Criteria) this;
}
public Criteria andEmpNameNotBetween(String value1, String value2) {
addCriterion("emp_name not between", value1, value2, "empName");
return (Criteria) this;
}
public Criteria andAgeIsNull() {
addCriterion("age is null");
return (Criteria) this;
}
public Criteria andAgeIsNotNull() {
addCriterion("age is not null");
return (Criteria) this;
}
public Criteria andAgeEqualTo(Integer value) {
addCriterion("age =", value, "age");
return (Criteria) this;
}
public Criteria andAgeNotEqualTo(Integer value) {
addCriterion("age <>", value, "age");
return (Criteria) this;
}
public Criteria andAgeGreaterThan(Integer value) {
addCriterion("age >", value, "age");
return (Criteria) this;
}
public Criteria andAgeGreaterThanOrEqualTo(Integer value) {
addCriterion("age >=", value, "age");
return (Criteria) this;
}
public Criteria andAgeLessThan(Integer value) {
addCriterion("age <", value, "age");
return (Criteria) this;
}
public Criteria andAgeLessThanOrEqualTo(Integer value) {
addCriterion("age <=", value, "age");
return (Criteria) this;
}
public Criteria andAgeIn(List<Integer> values) {
addCriterion("age in", values, "age");
return (Criteria) this;
}
public Criteria andAgeNotIn(List<Integer> values) {
addCriterion("age not in", values, "age");
return (Criteria) this;
}
public Criteria andAgeBetween(Integer value1, Integer value2) {
addCriterion("age between", value1, value2, "age");
return (Criteria) this;
}
public Criteria andAgeNotBetween(Integer value1, Integer value2) {
addCriterion("age not between", value1, value2, "age");
return (Criteria) this;
}
public Criteria andGenderIsNull() {
addCriterion("gender is null");
return (Criteria) this;
}
public Criteria andGenderIsNotNull() {
addCriterion("gender is not null");
return (Criteria) this;
}
public Criteria andGenderEqualTo(String value) {
addCriterion("gender =", value, "gender");
return (Criteria) this;
}
public Criteria andGenderNotEqualTo(String value) {
addCriterion("gender <>", value, "gender");
return (Criteria) this;
}
public Criteria andGenderGreaterThan(String value) {
addCriterion("gender >", value, "gender");
return (Criteria) this;
}
public Criteria andGenderGreaterThanOrEqualTo(String value) {
addCriterion("gender >=", value, "gender");
return (Criteria) this;
}
public Criteria andGenderLessThan(String value) {
addCriterion("gender <", value, "gender");
return (Criteria) this;
}
public Criteria andGenderLessThanOrEqualTo(String value) {
addCriterion("gender <=", value, "gender");
return (Criteria) this;
}
public Criteria andGenderLike(String value) {
addCriterion("gender like", value, "gender");
return (Criteria) this;
}
public Criteria andGenderNotLike(String value) {
addCriterion("gender not like", value, "gender");
return (Criteria) this;
}
public Criteria andGenderIn(List<String> values) {
addCriterion("gender in", values, "gender");
return (Criteria) this;
}
public Criteria andGenderNotIn(List<String> values) {
addCriterion("gender not in", values, "gender");
return (Criteria) this;
}
public Criteria andGenderBetween(String value1, String value2) {
addCriterion("gender between", value1, value2, "gender");
return (Criteria) this;
}
public Criteria andGenderNotBetween(String value1, String value2) {
addCriterion("gender not between", value1, value2, "gender");
return (Criteria) this;
}
public Criteria andDeptIdIsNull() {
addCriterion("dept_id is null");
return (Criteria) this;
}
public Criteria andDeptIdIsNotNull() {
addCriterion("dept_id is not null");
return (Criteria) this;
}
public Criteria andDeptIdEqualTo(Integer value) {
addCriterion("dept_id =", value, "deptId");
return (Criteria) this;
}
public Criteria andDeptIdNotEqualTo(Integer value) {
addCriterion("dept_id <>", value, "deptId");
return (Criteria) this;
}
public Criteria andDeptIdGreaterThan(Integer value) {
addCriterion("dept_id >", value, "deptId");
return (Criteria) this;
}
public Criteria andDeptIdGreaterThanOrEqualTo(Integer value) {
addCriterion("dept_id >=", value, "deptId");
return (Criteria) this;
}
public Criteria andDeptIdLessThan(Integer value) {
addCriterion("dept_id <", value, "deptId");
return (Criteria) this;
}
public Criteria andDeptIdLessThanOrEqualTo(Integer value) {
addCriterion("dept_id <=", value, "deptId");
return (Criteria) this;
}
public Criteria andDeptIdIn(List<Integer> values) {
addCriterion("dept_id in", values, "deptId");
return (Criteria) this;
}
public Criteria andDeptIdNotIn(List<Integer> values) {
addCriterion("dept_id not in", values, "deptId");
return (Criteria) this;
}
public Criteria andDeptIdBetween(Integer value1, Integer value2) {
addCriterion("dept_id between", value1, value2, "deptId");
return (Criteria) this;
}
public Criteria andDeptIdNotBetween(Integer value1, Integer value2) {
addCriterion("dept_id not between", value1, value2, "deptId");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
EmpMapper.java
在generatorConfig.xml中如果 targetRuntime=“MyBatis3”,会生成实体类和它的Example
MyBatis3Simple:生成基本的CRUD
MyBatis3:生成带条件的CRUD
有了EmpExample就可以对单表进行条件查询
package com.bijing.mybatis.mapper;
import com.bijing.mybatis.pojo.Emp;
import com.bijing.mybatis.pojo.EmpExample;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface EmpMapper {
long countByExample(EmpExample example);
//按条件删除
int deleteByExample(EmpExample example);
//按主键删除
int deleteByPrimaryKey(Integer empId);
int insert(Emp row);
//选择性添加
int insertSelective(Emp row);
List<Emp> selectByExample(EmpExample example);
Emp selectByPrimaryKey(Integer empId);
//选择性修改,某个属性为null的时候不会修改这个字段
int updateByExampleSelective(@Param("row") Emp row, @Param("example") EmpExample example);
//普通修改,某个属性为null的时候会将字段修改为null
int updateByExample(@Param("row") Emp row, @Param("example") EmpExample example);
int updateByPrimaryKeySelective(Emp row);
int updateByPrimaryKey(Emp row);
}