Mybatis Generator 使用手册
第一章 什么是Mybatis Generator?
MyBatis Generator Core – Introduction to MyBatis Generator
MyBatis生成器(MBG)是MyBatis框架的代码生成工具。它支持为所有版本的MyBatis生成代码,通过解析数据库表(或多个表)结构,自动生成用于访问这些表的相关组件。这有效减轻了手动配置对象和配置文件以实现数据库表交互的初始繁琐工作。MBG主要致力于简化大量基础性的数据库操作——即常见的增删改查(CRUD)操作。但对于涉及联合查询或存储过程等复杂场景,仍需开发者手动编写SQL和对象。
尽管限制新版本的MBG可以生成带注解版本(不包含xml)的Java代码,但是注解实现复杂场景(表join查询)时不是太方便,所以一般推荐使用传统版本的xml配置文件进行映射。
第二章 Mybatis Generator 各版本的功能?
我们主要使用的两个版本:
MyBatis3DynamicSQL:可生成不带xml配置的Java注解版代码。
Mybatis3:生成传统的使用XML进行映射的访问数据库代码。
Runtime | MyBatis Generator Version | MyBatis Version | MyBatis Dynamic SQL Version |
---|---|---|---|
MyBatis3, MyBatis3Simple | Any | 3.0+ | N/A |
MyBatis3DynamicSQL | 1.3.6 - 1.3.7 | 3.4.2+ | 1.1.0 - 1.2.1 |
MyBatis3DynamicSQL, MyBatis3Kotlin | 1.4.0 | 3.4.2+ | 1.1.3+ |
MyBatis3DynamicSQL | 1.4.1+ | 3.4.2+ | 1.3.1+ |
MyBatis3Kotlin | 1.4.1+ | 3.4.2+ | 1.4.0+ |
通常我们使用maven插件来进行代码的生成,多次运行代码Mybatis Generator的处理方式。
注意:当Mapper.java或者Mapper.xml有改动时,默认情况下时自动合并xml文件(保留已经修改的内容),但是Mapper.java会生成一个新的带版本的java文件(比如Mapper.java.1),需要手动合并。
比较推荐的做法是:使用原生的生成文件不做任何改动,需要修改时使用MapperExt.java, MapperExt.xml进行修改。这样省去了合并代码的工作。
第三章 怎样使用Mybatis Genrator?
3.1.引入依赖
<dependencies><dependency><groupId>jakarta.annotation</groupId><artifactId>jakarta.annotation-api</artifactId><version>2.1.1</version><scope>provided</scope></dependency><!-- MyBatis 核心依赖 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.13</version></dependency><!-- MySQL 连接器依赖 --><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><version>8.4.0</version></dependency><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><version>5.11.4</version><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-maven-plugin</artifactId><version>1.4.2</version><configuration><configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile></configuration><dependencies><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><version>8.4.0</version></dependency></dependencies></plugin></plugins></build>
此处数据库默认使用的MySQL,所以引入mysql的driver. 同时使用maven运行mybatis generator,加入maven mybatis-generator-maven-plugin.
3.2 加入配置文件
配置文件名称: mybatis-generator-config.xml
<!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="mybatis3" targetRuntime="MyBatis3"><jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"connectionURL="jdbc:mysql://localhost:3306/test_db"userId="user_name"password="my_password"/><javaModelGenerator targetPackage="com.my.model" targetProject="src/main/java"/><sqlMapGenerator targetPackage="com.my.mapper" targetProject="src/main/resources"/><javaClientGenerator type="XMLMAPPER" targetPackage="com.my.mapper" targetProject="src/main/java"/><table tableName="t_user" domainObjectName="User" /><table tableName="t_teacher" domainObjectName="Teacher" /><table tableName="t_student" domainObjectName="Student" /></context>
</generatorConfiguration>
根据配置文件中的内容,修改自己的数据库连接信息,需要放置的包名称,需要生成的表名称。
3.运行命令
mvn mybatis-generator:generate
然后代码就自动生成了。就可以完美的进行单表操作了。
第四章 生成代码的使用?
生成的Mapper.xml就不看了,写得很棒很专业。我们需要看看Mapper.java 和Example类,这样可以知道生成的类怎样使用?
4.1 UserExample类
下面以User的Example类进行说明,该类的含义和使用。
package com.my.model;import java.util.ArrayList;
import java.util.Date;
import java.util.List;public class UserExample {/*** This field was generated by MyBatis Generator.* This field corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/protected String orderByClause;/*** This field was generated by MyBatis Generator.* This field corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/protected boolean distinct;/*** This field was generated by MyBatis Generator.* This field corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/protected List<Criteria> oredCriteria;/*** This method was generated by MyBatis Generator.* This method corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public UserExample() {oredCriteria = new ArrayList<>();}/*** This method was generated by MyBatis Generator.* This method corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public void setOrderByClause(String orderByClause) {this.orderByClause = orderByClause;}/*** This method was generated by MyBatis Generator.* This method corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public String getOrderByClause() {return orderByClause;}/*** This method was generated by MyBatis Generator.* This method corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public void setDistinct(boolean distinct) {this.distinct = distinct;}/*** This method was generated by MyBatis Generator.* This method corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public boolean isDistinct() {return distinct;}/*** This method was generated by MyBatis Generator.* This method corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public List<Criteria> getOredCriteria() {return oredCriteria;}/*** This method was generated by MyBatis Generator.* This method corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public void or(Criteria criteria) {oredCriteria.add(criteria);}/*** This method was generated by MyBatis Generator.* This method corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/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 user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public Criteria createCriteria() {Criteria criteria = createCriteriaInternal();if (oredCriteria.size() == 0) {oredCriteria.add(criteria);}return criteria;}.../*** This class was generated by MyBatis Generator.* This class corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/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);}}
}
这个Example类,主要是使用Critiertion(单个的查询条件)和Critiera(多个查询条件)的封装类。
- 查询条件Critera --> List<Criterition>
- setDistinct 设置是否去重
- setOrderByClause(**) 设置排序的字段
使用它的方式如下:
UserExample example = new UserExample();
// 构建第一个and条件连接的查询链
example.createCretiar().andCreatedByEqualTo("jack.zhang");
// 构建第二个包含or里的 ( and 条件链)
example.or().anUserNameIsEqualTo("name");
// 设置去重
example.setDistinct(true)
// 设置排序字段
example.setOrderByClause("USER_NAME DESC");
生成的SQL语句如下:
select distinct USER_ID, USER_NAME, AGE, CREATED_TIME, CREATED_BY
from user
WHERE ( CREATED_BY = ? ) or ( USER_NAME = ? )
order by USER_ID ASC
4.2 UserMapper.java类
package com.keyrus.mapper;import com.keyrus.model.User;
import com.keyrus.model.UserExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;public interface UserMapper {/*** This method was generated by MyBatis Generator.* This method corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/long countByExample(UserExample example);/*** This method was generated by MyBatis Generator.* This method corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/int deleteByExample(UserExample example);/*** This method was generated by MyBatis Generator.* This method corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/int deleteByPrimaryKey(Integer userId);/*** This method was generated by MyBatis Generator.* This method corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/int insert(User row);/*** This method was generated by MyBatis Generator.* This method corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/int insertSelective(User row);/*** This method was generated by MyBatis Generator.* This method corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/List<User> selectByExample(UserExample example);/*** This method was generated by MyBatis Generator.* This method corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/User selectByPrimaryKey(Integer userId);/*** This method was generated by MyBatis Generator.* This method corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/int updateByExampleSelective(@Param("row") User row, @Param("example") UserExample example);/*** This method was generated by MyBatis Generator.* This method corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/int updateByExample(@Param("row") User row, @Param("example") UserExample example);/*** This method was generated by MyBatis Generator.* This method corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/int updateByPrimaryKeySelective(User row);/*** This method was generated by MyBatis Generator.* This method corresponds to the database table user** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/int updateByPrimaryKey(User row);
}
按照新增/修改/查询/删除的顺序,方法归纳如下:
insert(User user) 插入整个User对象;
insertSelective(User user) 插入部分字段;
updateByPrimaryKey(User user) 根据主键更新User;
updateByPrimaryKeySelective (User user) 根据主键部分更新User的字段;
updateByExampleSelective(User user, UserExample example) 根据example条件筛选出记录进行部分user字段的更新。
selectByPrimaryKey(id) 根据主键查询User;
selectByExample(UserExample exapmle) 根据example条件筛选查询User;
countByExample(UserExample example) 根据example条件查询统计记录数目;
deleteByPrimaryKey(id) 根据主键进行删除单条记录;
deleteByExample(UserExample example) 根据example条件筛选出多条记录进行删除;
基本上上面的四类方法,包含了日常单表的所有操作。
有复杂的表与表直接的操作,需要自己手写去完成。