11.1、正向与逆向工程概述

  • 正向工程:先创建Java实体类,由框架负责根据实体类生成数据库表;例如Hibernate是支持正向工程的。

  • 逆向工程:先创建数据库表,由框架负责根据数据库表,反向生成Java实体类、mapper接口和映射文件。

11.2、环境搭建

11.2.1、创建新module

创建名为mybatis_mbg的新module,过程参考5.1节

11.2.2、添加打包方式和依赖及插件

<?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>org.rain</groupId>
<artifactId>mybatis_mbg</artifactId>
<version>1.0-SNAPSHOT</version>
<!--打包方式-->
<packaging>jar</packaging> <!--依赖-->
<dependencies>
<!-- Mybatis核心 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!-- log4j日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies> <build>
<!-- 构建过程中用到的插件 -->
<plugins>
<!-- 具体插件,逆向工程的操作是以构建过程中插件形式出现的 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.0</version>
<!-- 插件的依赖 -->
<dependencies>
<!-- 逆向工程的核心依赖 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build> </project>

11.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>
<!--
targetRuntime属性: 设置执行生成逆向工程的版本
MyBatis3Simple: 生成基本的CRUD(简洁版)
MyBatis3: 生成带条件的CRUD(进阶版)
-->
<context id="DB2Tables" targetRuntime="MyBatis3Simple">
<!-- 数据库的连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8"
userId="root"
password="root">
</jdbcConnection>
<!-- javaBean的生成策略-->
<javaModelGenerator targetPackage="org.rain.mybatis.pojo" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- SQL映射文件的生成策略 -->
<sqlMapGenerator targetPackage="org.rain.mybatis.mapper" targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- Mapper接口的生成策略 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="org.rain.mybatis.mapper" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 逆向分析的表 -->
<!-- tableName设置为*号,可以对应所有表,此时不写domainObjectName -->
<!-- domainObjectName属性指定生成出来的实体类的类名 -->
<table tableName="t_emp" domainObjectName="Emp"/>
<table tableName="t_dept" domainObjectName="Dept"/>
</context>
</generatorConfiguration>

11.4、执行mybatis-generator插件

  • 找到mybatis-generator插件,并双击执行

11.5、插件执行效果(简洁版)

11.5.1、总体概览

注意:如图所示,实体类、接口和映射文件都自动生成了

11.5.2、实体类生成内容示例

package org.rain.mybatis.pojo;

public class Dept {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column t_dept.dept_id
*
* @mbggenerated Wed Jul 05 11:25:17 CST 2023
*/
private Integer deptId; /**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column t_dept.dept_name
*
* @mbggenerated Wed Jul 05 11:25:17 CST 2023
*/
private String deptName; /**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column t_dept.dept_id
*
* @return the value of t_dept.dept_id
*
* @mbggenerated Wed Jul 05 11:25:17 CST 2023
*/
public Integer getDeptId() {
return deptId;
} /**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column t_dept.dept_id
*
* @param deptId the value for t_dept.dept_id
*
* @mbggenerated Wed Jul 05 11:25:17 CST 2023
*/
public void setDeptId(Integer deptId) {
this.deptId = deptId;
} /**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column t_dept.dept_name
*
* @return the value of t_dept.dept_name
*
* @mbggenerated Wed Jul 05 11:25:17 CST 2023
*/
public String getDeptName() {
return deptName;
} /**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column t_dept.dept_name
*
* @param deptName the value for t_dept.dept_name
*
* @mbggenerated Wed Jul 05 11:25:17 CST 2023
*/
public void setDeptName(String deptName) {
this.deptName = deptName == null ? null : deptName.trim();
}
}

11.5.3、mapper接口生成内容示例

package org.rain.mybatis.mapper;

import java.util.List;
import org.rain.mybatis.pojo.Dept; public interface DeptMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Wed Jul 05 11:25:17 CST 2023
*/
int deleteByPrimaryKey(Integer deptId); /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Wed Jul 05 11:25:17 CST 2023
*/
int insert(Dept record); /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Wed Jul 05 11:25:17 CST 2023
*/
Dept selectByPrimaryKey(Integer deptId); /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Wed Jul 05 11:25:17 CST 2023
*/
List<Dept> selectAll(); /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Wed Jul 05 11:25:17 CST 2023
*/
int updateByPrimaryKey(Dept record);
}

11.5.4、映射文件生成内容示例

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="org.rain.mybatis.mapper.DeptMapper" >
<resultMap id="BaseResultMap" type="org.rain.mybatis.pojo.Dept" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Wed Jul 05 11:25:17 CST 2023.
-->
<id column="dept_id" property="deptId" jdbcType="INTEGER" />
<result column="dept_name" property="deptName" jdbcType="VARCHAR" />
</resultMap>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Wed Jul 05 11:25:17 CST 2023.
-->
delete from t_dept
where dept_id = #{deptId,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="org.rain.mybatis.pojo.Dept" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Wed Jul 05 11:25:17 CST 2023.
-->
insert into t_dept (dept_id, dept_name)
values (#{deptId,jdbcType=INTEGER}, #{deptName,jdbcType=VARCHAR})
</insert>
<update id="updateByPrimaryKey" parameterType="org.rain.mybatis.pojo.Dept" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Wed Jul 05 11:25:17 CST 2023.
-->
update t_dept
set dept_name = #{deptName,jdbcType=VARCHAR}
where dept_id = #{deptId,jdbcType=INTEGER}
</update>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Wed Jul 05 11:25:17 CST 2023.
-->
select dept_id, dept_name
from t_dept
where dept_id = #{deptId,jdbcType=INTEGER}
</select>
<select id="selectAll" resultMap="BaseResultMap" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Wed Jul 05 11:25:17 CST 2023.
-->
select dept_id, dept_name
from t_dept
</select>
</mapper>

11.6、进阶版逆向工程

11.6.1、修改逆向工程配置文件

11.6.2、删除之前简单版生成的内容

++++++++++++++++++++分割线++++++++++++++++++++++

11.6.3、执行mybatis-generator插件

11.6.4、插件执行效果(进阶版)

11.6.4.1、总体概览

注意:进阶版生成的实体类,比简洁版的多了xxxExample

11.6.4.2、实体类生成内容示例

package org.rain.mybatis.pojo;

public class Dept {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column t_dept.dept_id
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
private Integer deptId; /**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column t_dept.dept_name
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
private String deptName; /**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column t_dept.dept_id
*
* @return the value of t_dept.dept_id
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
public Integer getDeptId() {
return deptId;
} /**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column t_dept.dept_id
*
* @param deptId the value for t_dept.dept_id
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
public void setDeptId(Integer deptId) {
this.deptId = deptId;
} /**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column t_dept.dept_name
*
* @return the value of t_dept.dept_name
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
public String getDeptName() {
return deptName;
} /**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column t_dept.dept_name
*
* @param deptName the value for t_dept.dept_name
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
public void setDeptName(String deptName) {
this.deptName = deptName == null ? null : deptName.trim();
}
}

11.6.4.3、实体类Example生成内容示例

package org.rain.mybatis.pojo;

import java.util.ArrayList;
import java.util.List; public class DeptExample {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
protected String orderByClause; /**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
protected boolean distinct; /**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
protected List<Criteria> oredCriteria; /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
public DeptExample() {
oredCriteria = new ArrayList<Criteria>();
} /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
} /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
public String getOrderByClause() {
return orderByClause;
} /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
} /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
public boolean isDistinct() {
return distinct;
} /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
public List<Criteria> getOredCriteria() {
return oredCriteria;
} /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
} /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
} /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
} /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
} /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
} /**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria; protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
} 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 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 Criteria andDeptNameIsNull() {
addCriterion("dept_name is null");
return (Criteria) this;
} public Criteria andDeptNameIsNotNull() {
addCriterion("dept_name is not null");
return (Criteria) this;
} public Criteria andDeptNameEqualTo(String value) {
addCriterion("dept_name =", value, "deptName");
return (Criteria) this;
} public Criteria andDeptNameNotEqualTo(String value) {
addCriterion("dept_name <>", value, "deptName");
return (Criteria) this;
} public Criteria andDeptNameGreaterThan(String value) {
addCriterion("dept_name >", value, "deptName");
return (Criteria) this;
} public Criteria andDeptNameGreaterThanOrEqualTo(String value) {
addCriterion("dept_name >=", value, "deptName");
return (Criteria) this;
} public Criteria andDeptNameLessThan(String value) {
addCriterion("dept_name <", value, "deptName");
return (Criteria) this;
} public Criteria andDeptNameLessThanOrEqualTo(String value) {
addCriterion("dept_name <=", value, "deptName");
return (Criteria) this;
} public Criteria andDeptNameLike(String value) {
addCriterion("dept_name like", value, "deptName");
return (Criteria) this;
} public Criteria andDeptNameNotLike(String value) {
addCriterion("dept_name not like", value, "deptName");
return (Criteria) this;
} public Criteria andDeptNameIn(List<String> values) {
addCriterion("dept_name in", values, "deptName");
return (Criteria) this;
} public Criteria andDeptNameNotIn(List<String> values) {
addCriterion("dept_name not in", values, "deptName");
return (Criteria) this;
} public Criteria andDeptNameBetween(String value1, String value2) {
addCriterion("dept_name between", value1, value2, "deptName");
return (Criteria) this;
} public Criteria andDeptNameNotBetween(String value1, String value2) {
addCriterion("dept_name not between", value1, value2, "deptName");
return (Criteria) this;
}
} /**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table t_dept
*
* @mbggenerated do_not_delete_during_merge Thu Jul 06 11:01:56 CST 2023
*/
public static class Criteria extends GeneratedCriteria { protected Criteria() {
super();
}
} /**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
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);
}
}
}

11.6.4.4、mapper接口生成内容示例

package org.rain.mybatis.mapper;

import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.rain.mybatis.pojo.Dept;
import org.rain.mybatis.pojo.DeptExample; public interface DeptMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
int countByExample(DeptExample example); /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
int deleteByExample(DeptExample example); /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
int deleteByPrimaryKey(Integer deptId); /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
int insert(Dept record); /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
int insertSelective(Dept record); /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
List<Dept> selectByExample(DeptExample example); /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
Dept selectByPrimaryKey(Integer deptId); /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
int updateByExampleSelective(@Param("record") Dept record, @Param("example") DeptExample example); /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
int updateByExample(@Param("record") Dept record, @Param("example") DeptExample example); /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
int updateByPrimaryKeySelective(Dept record); /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_dept
*
* @mbggenerated Thu Jul 06 11:01:56 CST 2023
*/
int updateByPrimaryKey(Dept record);
}

11.6.4.5、映射文件生成内容示例

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="org.rain.mybatis.mapper.DeptMapper" >
<resultMap id="BaseResultMap" type="org.rain.mybatis.pojo.Dept" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Thu Jul 06 11:01:56 CST 2023.
-->
<id column="dept_id" property="deptId" jdbcType="INTEGER" />
<result column="dept_name" property="deptName" jdbcType="VARCHAR" />
</resultMap>
<sql id="Example_Where_Clause" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Thu Jul 06 11:01:56 CST 2023.
-->
<where >
<foreach collection="oredCriteria" item="criteria" separator="or" >
<if test="criteria.valid" >
<trim prefix="(" suffix=")" prefixOverrides="and" >
<foreach collection="criteria.criteria" item="criterion" >
<choose >
<when test="criterion.noValue" >
and ${criterion.condition}
</when>
<when test="criterion.singleValue" >
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue" >
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue" >
and ${criterion.condition}
<foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Thu Jul 06 11:01:56 CST 2023.
-->
<where >
<foreach collection="example.oredCriteria" item="criteria" separator="or" >
<if test="criteria.valid" >
<trim prefix="(" suffix=")" prefixOverrides="and" >
<foreach collection="criteria.criteria" item="criterion" >
<choose >
<when test="criterion.noValue" >
and ${criterion.condition}
</when>
<when test="criterion.singleValue" >
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue" >
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue" >
and ${criterion.condition}
<foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Thu Jul 06 11:01:56 CST 2023.
-->
dept_id, dept_name
</sql>
<select id="selectByExample" resultMap="BaseResultMap" parameterType="org.rain.mybatis.pojo.DeptExample" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Thu Jul 06 11:01:56 CST 2023.
-->
select
<if test="distinct" >
distinct
</if>
<include refid="Base_Column_List" />
from t_dept
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null" >
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Thu Jul 06 11:01:56 CST 2023.
-->
select
<include refid="Base_Column_List" />
from t_dept
where dept_id = #{deptId,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Thu Jul 06 11:01:56 CST 2023.
-->
delete from t_dept
where dept_id = #{deptId,jdbcType=INTEGER}
</delete>
<delete id="deleteByExample" parameterType="org.rain.mybatis.pojo.DeptExample" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Thu Jul 06 11:01:56 CST 2023.
-->
delete from t_dept
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="org.rain.mybatis.pojo.Dept" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Thu Jul 06 11:01:56 CST 2023.
-->
insert into t_dept (dept_id, dept_name)
values (#{deptId,jdbcType=INTEGER}, #{deptName,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="org.rain.mybatis.pojo.Dept" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Thu Jul 06 11:01:56 CST 2023.
-->
insert into t_dept
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="deptId != null" >
dept_id,
</if>
<if test="deptName != null" >
dept_name,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="deptId != null" >
#{deptId,jdbcType=INTEGER},
</if>
<if test="deptName != null" >
#{deptName,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="org.rain.mybatis.pojo.DeptExample" resultType="java.lang.Integer" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Thu Jul 06 11:01:56 CST 2023.
-->
select count(*) from t_dept
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Thu Jul 06 11:01:56 CST 2023.
-->
update t_dept
<set >
<if test="record.deptId != null" >
dept_id = #{record.deptId,jdbcType=INTEGER},
</if>
<if test="record.deptName != null" >
dept_name = #{record.deptName,jdbcType=VARCHAR},
</if>
</set>
<if test="_parameter != null" >
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Thu Jul 06 11:01:56 CST 2023.
-->
update t_dept
set dept_id = #{record.deptId,jdbcType=INTEGER},
dept_name = #{record.deptName,jdbcType=VARCHAR}
<if test="_parameter != null" >
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="org.rain.mybatis.pojo.Dept" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Thu Jul 06 11:01:56 CST 2023.
-->
update t_dept
<set >
<if test="deptName != null" >
dept_name = #{deptName,jdbcType=VARCHAR},
</if>
</set>
where dept_id = #{deptId,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="org.rain.mybatis.pojo.Dept" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Thu Jul 06 11:01:56 CST 2023.
-->
update t_dept
set dept_name = #{deptName,jdbcType=VARCHAR}
where dept_id = #{deptId,jdbcType=INTEGER}
</update>
</mapper>

11.7、测试示例

11.7.1、引入相关配置文件

11.7.1.1、jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

11.7.1.2、mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource="jdbc.properties"/> <settings>
<!--将下划线映射为驼峰-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!--开启延迟加载-->
<!--<setting name="lazyLoadingEnabled" value="true"/>-->
<!--开启二级缓存-->
<setting name="cacheEnabled" value="true"/>
</settings> <typeAliases>
<package name="org.rain.mybatis.pojo"/>
</typeAliases> <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> <mappers>
<package name="org.rain.mybatis.mapper"/>
</mappers> </configuration>

11.7.1.3、log4j.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>

11.7.2、创建获取SqlSession工具类

package org.rain.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException;
import java.io.InputStream; public class SqlSessionUtils {
public static SqlSession getSqlSession(){
SqlSession sqlSession = null; try {
//读取MyBatis核心配置文件的输入流
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//通过核心配置文件所对应的字节输入流创建工厂类SqlSessionFactory,用于生产SqlSession对象
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//创建自动提交事务的SqlSession对象
sqlSession = sqlSessionFactory.openSession(true);
} catch (IOException e) {
e.printStackTrace();
}
return sqlSession;
}
}

11.7.3、创建测试类

11.7.4、根据主键查询一条数据

注意:生成的实体类没有tostring方法,因此需要手动在实体类添加tostring方法才有相关输出

    @Test
public void testMbg(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class); //根据主键查询一条数据
Emp emp = empMapper.selectByPrimaryKey(1);
System.out.println(emp); }

11.7.5、查询所有数据

注意:无条件查询(即xxxExample为null)就是查询所有

    @Test
public void testMbg(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class); //查询所有数据
List<Emp> emps = empMapper.selectByExample(null);
for (Emp emp : emps) {
System.out.println(emp);
} }

11.7.6、多条件查询(QBC风格)

    @Test
public void testMbg(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class); //多条件查询,QBC(query by condition)风格
EmpExample empExample = new EmpExample();
empExample.createCriteria().andEmpNameEqualTo("小红").andEmpIdBetween(8,10);
empExample.or().andAgeEqualTo(20);
List<Emp> emps = empMapper.selectByExample(empExample);
for (Emp emp : emps) {
System.out.println(emp);
} }

11.7.7、普通修改

++++++++++++++++++++++++分割线++++++++++++++++++++++++

++++++++++++++++++++++++分割线++++++++++++++++++++++++

注意:如图所示,普通修改会将显式设置为null或未设置的字段都修改为null

    @Test
public void testMbg(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class); Emp emp = new Emp();
emp.setEmpId(4);
emp.setEmpName("小军");
emp.setAge(null);
emp.setGender("女");
empMapper.updateByPrimaryKey(emp);
}

11.7.8、选择性修改

++++++++++++++++++++++++分割线++++++++++++++++++++++++

++++++++++++++++++++++++分割线++++++++++++++++++++++++

注意:如图所示,选择性修改不会将显式设置为null或未设置的字段修改为null

    @Test
public void testMbg(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class); Emp emp = new Emp();
emp.setEmpId(3);
emp.setEmpName("小军");
emp.setAge(null);
emp.setGender("女");
empMapper.updateByPrimaryKeySelective(emp);
}

11、Mybatis之逆向工程的更多相关文章

  1. mybatis学习系列四--mybatis generator逆向工程

    采用命令行方式执行逆向工程 1.配置文件generatorConfig.xml 保存在目录:D:\E\workspace\eclipse\mybatis_generator <?xmlversi ...

  2. 创建mybatis的逆向工程

    1.mybatis的逆向工程(我使用的是maven仓库创建) 工作原理:反向工程(通过数据库中的表和字段信息去生成对应的增删改查方法) 其实就是一个自动生成工具 生成实体类(pojo)和映射文件(ma ...

  3. mybatis的逆向工程

    mybatis的逆向工程是很大的减少了程序员对代码的编写工作,由于mybatis是半自动的sql语句使用,我们在项目中一般都是采用逆向工程来生成mybatis的文件,mapper接口相当于我们平常所说 ...

  4. Mybatis(七) mybatis的逆向工程的配置详解

    还是觉得看书学习有意思~嘿嘿.今天把mybatis给结束掉. --WH 一.什么是逆向工程? 简单点说,就是通过数据库中的单表,自动生成java代码. Mybatis官方提供了逆向工程,可以针对单表自 ...

  5. Mybatis【逆向工程,缓存,代理】知识要点

    前言 本文主要讲解Mybatis的以下知识点: Mybatis缓存 一级缓存 二级缓存 与Ehcache整合 Mapper代理 使用Mapper代理就不用写实现类了 逆向工程 自动生成代码 Mybat ...

  6. Mybatis学习(七)————— mybatis的逆向工程的配置详解

    一.什么是逆向工程? 简单点说,就是通过数据库中的单表,自动生成java代码. Mybatis官方提供了逆向工程,可以针对单表自动生成mybatis代码(mapper.java\mapper.xml\ ...

  7. SpringBoot+Mybatis+Generator 逆向工程使用(二)

    Mybatis-Genarator 逆向工程使用 个人开发环境 java环境:Jdk1.8.0_60 编译器:IntelliJ IDEA 2017.1.4 mysql驱动:mysql-connecto ...

  8. 【MyBatis学习15】MyBatis的逆向工程生成代码

    1. 什么是逆向工程 mybatis的一个主要的特点就是需要程序员自己编写sql,那么如果表太多的话,难免会很麻烦,所以mybatis官方提供了一个逆向工程,可以针对单表自动生成mybatis执行所需 ...

  9. Mybatis的逆向工程以及Example的实例函数及详解

    Mybatis-generator是Mybatis的逆向工程  (根据数据库中的表生成java代码) Mybatis的逆向工程会生成实例及实例对应的example,example用于添加条件,相当于w ...

  10. Mybatis Generator逆向工程的使用

    一.在 idea 中使用 mybatis generator 逆向工程 1.在IDEA上创建maven工程. 2.在pom.xml中配置MyBatis逆向工程插件 <!--MyBatis自动生成 ...

随机推荐

  1. 2021-11-19:[0,4,7] : 0表示这里石头没有颜色,如果变红代价是4,如果变蓝代价是7,[1,X,X] : 1表示这里石头已经是红,而且不能改颜色,所以后两个数X无意义,[2,X,X]

    2021-11-19:[0,4,7] : 0表示这里石头没有颜色,如果变红代价是4,如果变蓝代价是7,[1,X,X] : 1表示这里石头已经是红,而且不能改颜色,所以后两个数X无意义,[2,X,X] ...

  2. 2021-08-01:如果只给定一个二叉树前序遍历数组pre和中序遍历数组in,能否不重建树,而直接生成这个二叉树的后序数组并返回。已知二叉树中没有重复值。

    2021-08-01:如果只给定一个二叉树前序遍历数组pre和中序遍历数组in,能否不重建树,而直接生成这个二叉树的后序数组并返回.已知二叉树中没有重复值. 福大大 答案2021-08-01: 先序遍 ...

  3. <form>表单中的action和method使用方法

    <form action="" method="post"> form是表单   里面的内容是要提交出去的. action 是链接   点击浏览选择 ...

  4. WSGI实现一个WEB服务

  5. LLM探索:环境搭建与模型本地部署

    前言 最近一直在炼丹(搞AIGC这块),突然发现业务代码都索然无味了- 上次发了篇AI画图的文章,ChatGPT虽然没法自己部署,但现在开源的LLM还是不少的,只要有一块差不多的显卡,要搞个LLM本地 ...

  6. 云原生时代Go最受欢迎Web开源框架Gin原理与实战

    @ 目录 概述 定义 特点 概览导图 使用 快速入门 HTTP 方法使用 参数获取 参数绑定 自定义日志输出 自定义中间件 路由组 HTML渲染 设置和获取Cookie XML.YAML.ProtoB ...

  7. 深入解析React DnD拖拽原理,轻松掌握拖放技巧!

    我们是袋鼠云数栈 UED 团队,致力于打造优秀的一站式数据中台产品.我们始终保持工匠精神,探索前端道路,为社区积累并传播经验价值.. 本文作者:霁明 一.背景 1.业务背景 业务中会有一些需要实现拖拽 ...

  8. Java CAS:AtomicInteger、AtomicReference、AtomicStampedReference

    Java CAS:AtomicInteger.AtomicReference.AtomicStampedReference 什么是CAS? 什么是CAS? 即比较并替换,实现并发算法时常用到的一种技术 ...

  9. 【.NET源码解读】深入剖析中间件的设计与实现

    .NET本身就是一个基于中间件(middleware)的框架,它通过一系列的中间件组件来处理HTTP请求和响应.在之前的文章<.NET源码解读kestrel服务器及创建HttpContext对象 ...

  10. 即构SDK7月迭代:新增支持按通道设置延迟模式,让卡顿大大减少

    即构SDK 7月迭代如期而至,本月SDK更新主要增加了按推流通道设置延迟模式,大大减少了直播卡顿:媒体本地录制新增AAC 格式,可生成更小的录制文件,更易于上传.此外还有多项功能的优化,让用户获得更好 ...