MyBatis Generator(简称MBG)是MyBatis官方提供的代码生成工具。可以通过数据库表直接生成实体类、单表CRUD代码、mapper.xml文件,从而解放我们的双手!
首先我们通过一个入门示例将MBG用起来,该示例会包含基础的CRUD操作。
pom.xml中添加如下依赖,主要添加了MyBatis、PageHelper、Druid、MBG和MySQL驱动等依赖;|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<dependencies> <!--SpringBoot整合MyBatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> <!--MyBatis分页插件--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency> <!--集成druid连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <!-- MyBatis 生成器 --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.4.0</version> </dependency> <!--Mysql数据库驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.15</version> </dependency> </dependencies> |
application.yml中对数据源和MyBatis的mapper.xml文件路径进行配置,这里做个约定,MBG生成的放在resources/com/**/mapper目录下,自定义的放在resources/dao目录下;|
1 2 3 4 5 6 7 8 9 10 11 12 |
# 数据源配置 spring: datasource: url: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: root # MyBatis mapper.xml路径配置 mybatis: mapper-locations: - classpath:dao/*.xml - classpath*:com/**/mapper/*.xml |
mapper包下,自定义的放在dao包下。|
1 2 3 4 5 6 7 8 |
/** * MyBatis配置类 * Created by macro on 2019/4/8. */ @Configuration @MapperScan({"com.macro.mall.tiny.mbg.mapper","com.macro.mall.tiny.dao"}) public class MyBatisConfig { } |
generator.properties文件中配置好数据库连接信息;|
1 2 3 4 |
jdbc.driverClass=com.mysql.cj.jdbc.Driver jdbc.connectionURL=jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai jdbc.userId=root jdbc.password=root |
generatorConfig.xml文件中对MBG进行配置,配置属性说明直接参考注释即可;|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
<?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> <properties resource="generator.properties"/> <context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat"> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> <property name="javaFileEncoding" value="UTF-8"/> <!--生成mapper.xml时覆盖原文件--> <plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" /> <!-- 为模型生成序列化方法--> <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/> <!-- 为生成的Java模型创建一个toString方法 --> <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/> <!--可以自定义生成model的代码注释--> <commentGenerator type="com.macro.mall.tiny.mbg.CommentGenerator"> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true"/> <property name="suppressDate" value="true"/> <property name="addRemarkComments" value="true"/> </commentGenerator> <!--配置数据库连接--> <jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbc.connectionURL}" userId="${jdbc.userId}" password="${jdbc.password}"> <!--解决mysql驱动升级到8.0后不生成指定数据库代码的问题--> <property name="nullCatalogMeansCurrent" value="true" /> </jdbcConnection> <!--指定生成model的路径--> <javaModelGenerator targetPackage="com.macro.mall.tiny.mbg.model" targetProject="mall-tiny-generator\src\main\java"/> <!--指定生成mapper.xml的路径--> <sqlMapGenerator targetPackage="com.macro.mall.tiny.mbg.mapper" targetProject="mall-tiny-generator\src\main\resources"/> <!--指定生成mapper接口的的路径--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.macro.mall.tiny.mbg.mapper" targetProject="mall-tiny-generator\src\main\java"/> <!--生成全部表tableName设为%--> <table tableName="ums_admin"> <generatedKey column="id" sqlStatement="MySql" identity="true"/> </table> <table tableName="ums_role"> <generatedKey column="id" sqlStatement="MySql" identity="true"/> </table> <table tableName="ums_admin_role_relation"> <generatedKey column="id" sqlStatement="MySql" identity="true"/> </table> <table tableName="ums_resource"> <generatedKey column="id" sqlStatement="MySql" identity="true"/> </table> <table tableName="ums_resource_category"> <generatedKey column="id" sqlStatement="MySql" identity="true"/> </table> </context> </generatorConfiguration> |
targetRuntime这个属性,设置不同的属性生成的代码和生成代码的使用方式会有所不同,常用的有MyBatis3和MyBatis3DynamicSql两种,这里使用的是MyBatis3;|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
package com.macro.mall.tiny.mbg; import org.mybatis.generator.api.IntrospectedColumn; import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.dom.java.CompilationUnit; import org.mybatis.generator.api.dom.java.Field; import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; import org.mybatis.generator.internal.DefaultCommentGenerator; import org.mybatis.generator.internal.util.StringUtility; import java.util.Properties; /** * 自定义注释生成器 * Created by macro on 2018/4/26. */ public class CommentGenerator extends DefaultCommentGenerator { private boolean addRemarkComments = false; private static final String EXAMPLE_SUFFIX="Example"; private static final String MAPPER_SUFFIX="Mapper"; private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME="io.swagger.annotations.ApiModelProperty"; /** * 设置用户配置的参数 */ @Override public void addConfigurationProperties(Properties properties) { super.addConfigurationProperties(properties); this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments")); } /** * 给字段添加注释 */ @Override public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) { String remarks = introspectedColumn.getRemarks(); //根据参数和备注信息判断是否添加备注信息 if(addRemarkComments&&StringUtility.stringHasValue(remarks)){ //数据库中特殊字符需要转义 if(remarks.contains("\"")){ remarks = remarks.replace("\"","'"); } //给model的字段添加swagger注解 field.addJavaDocLine("@ApiModelProperty(value = \""+remarks+"\")"); } } @Override public void addJavaFileComment(CompilationUnit compilationUnit) { super.addJavaFileComment(compilationUnit); //只在model中添加swagger注解类的导入 String fullyQualifiedName = compilationUnit.getType().getFullyQualifiedName(); if(!fullyQualifiedName.contains(MAPPER_SUFFIX)&&!fullyQualifiedName.contains(EXAMPLE_SUFFIX)){ compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME)); } } } |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/** * 用于生产MBG的代码 * Created by macro on 2018/4/26. */ public class Generator { public static void main(String[] args) throws Exception { //MBG 执行过程中的警告信息 List<String> warnings = new ArrayList<String>(); //当生成的代码重复时,覆盖原代码 boolean overwrite = true; //读取我们的 MBG 配置文件 InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(is); is.close(); DefaultShellCallback callback = new DefaultShellCallback(overwrite); //创建 MBG MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); //执行生成代码 myBatisGenerator.generate(null); //输出警告信息 for (String warning : warnings) { System.out.println(warning); } } } |

这里使用的是
mall-tiny项目中权限管理功能相关表,具体可以参考《还在从零开始搭建项目?手撸了款快速开发脚手架!》。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public interface UmsAdminMapper { long countByExample(UmsAdminExample example); int deleteByExample(UmsAdminExample example); int deleteByPrimaryKey(Long id); int insert(UmsAdmin record); int insertSelective(UmsAdmin record); List<UmsAdmin> selectByExample(UmsAdminExample example); UmsAdmin selectByPrimaryKey(Long id); int updateByExampleSelective(@Param("record") UmsAdmin record, @Param("example") UmsAdminExample example); int updateByExample(@Param("record") UmsAdmin record, @Param("example") UmsAdminExample example); int updateByPrimaryKeySelective(UmsAdmin record); int updateByPrimaryKey(UmsAdmin record); } |

|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
/** * 后台用户管理Service实现类 * Created by macro on 2020/12/8. */ @Service public class UmsAdminServiceImpl implements UmsAdminService { @Autowired private UmsAdminMapper adminMapper; @Autowired private UmsAdminDao adminDao; @Override public void create(UmsAdmin entity) { adminMapper.insert(entity); } @Override public void update(UmsAdmin entity) { adminMapper.updateByPrimaryKeySelective(entity); } @Override public void delete(Long id) { adminMapper.deleteByPrimaryKey(id); } @Override public UmsAdmin select(Long id) { return adminMapper.selectByPrimaryKey(id); } @Override public List<UmsAdmin> listAll(Integer pageNum, Integer pageSize) { PageHelper.startPage(pageNum, pageSize); return adminMapper.selectByExample(new UmsAdminExample()); } } |
想要用好MBG,上面的基础操作是不够的,还需要一些进阶的使用技巧。
使用Example类构建查询条件可以很方便地实现条件查询。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
SELECT id, username, PASSWORD, icon, email, nick_name, note, create_time, login_time, STATUS FROM ums_admin WHERE ( username = 'macro' AND STATUS IN ( 0, 1 ) ) ORDER BY create_time DESC; |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
/** * 后台用户管理Service实现类 * Created by macro on 2020/12/8. */ @Service public class UmsAdminServiceImpl implements UmsAdminService { @Override public List<UmsAdmin> list(Integer pageNum, Integer pageSize, String username, List<Integer> statusList) { PageHelper.startPage(pageNum, pageSize); UmsAdminExample umsAdminExample = new UmsAdminExample(); UmsAdminExample.Criteria criteria = umsAdminExample.createCriteria(); if(StrUtil.isNotEmpty(username)){ criteria.andUsernameEqualTo(username); } criteria.andStatusIn(statusList); umsAdminExample.setOrderByClause("create_time desc"); return adminMapper.selectByExample(umsAdminExample); } } |
使用MBG生成的代码并不能实现子查询,需要自己手写SQL实现。
subList方法;|
1 2 3 4 5 6 7 |
/** * Created by macro on 2020/12/9. */ public interface UmsAdminDao { List<UmsAdmin> subList(@Param("roleId") Long roleId); } |
|
1 2 3 4 5 |
<select id="subList" resultMap="com.macro.mall.tiny.mbg.mapper.UmsAdminMapper.BaseResultMap"> SELECT * FROM ums_admin WHERE id IN (SELECT admin_id FROM ums_admin_role_relation WHERE role_id = #{roleId}) </select> |
Group和Join查询也不能使用MBG生成的代码实现。
groupList方法;|
1 2 3 4 |
public interface UmsAdminDao { List<RoleStatDto> groupList(); } |
|
1 2 3 4 5 6 7 8 9 |
<select id="groupList" resultType="com.macro.mall.tiny.domain.RoleStatDto"> SELECT ur.id AS roleId, ur.NAME AS roleName, count(ua.id) AS count FROM ums_role ur LEFT JOIN ums_admin_role_relation uarr ON ur.id = uarr.role_id LEFT JOIN ums_admin ua ON uarr.admin_id = ua.id GROUP BY ur.id; </select> |
条件删除很简单,直接使用Example类构造删除条件即可。
|
1 2 3 4 5 |
DELETE FROM ums_admin WHERE username = 'andy'; |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/** * 后台用户管理Service实现类 * Created by macro on 2020/12/8. */ @Service public class UmsAdminServiceImpl implements UmsAdminService { @Override public void deleteByUsername(String username) { UmsAdminExample example = new UmsAdminExample(); example.createCriteria().andUsernameEqualTo(username); adminMapper.deleteByExample(example); } } |
条件删除很简单,直接使用Example类构造修改条件,然后传入修改参数即可。
|
1 2 3 4 |
UPDATE ums_admin SET STATUS = 1 WHERE id IN ( 1, 2 ); |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
/** * 后台用户管理Service实现类 * Created by macro on 2020/12/8. */ @Service public class UmsAdminServiceImpl implements UmsAdminService { @Override public void updateByIds(List<Long> ids, Integer status) { UmsAdmin record = new UmsAdmin(); record.setStatus(status); UmsAdminExample example = new UmsAdminExample(); example.createCriteria().andIdIn(ids); adminMapper.updateByExampleSelective(record,example); } } |
一对多查询无法直接使用MBG生成的代码实现,需要手写SQL实现,并使用resultMap来进行结果集映射。
selectWithRoleList方法;|
1 2 3 4 5 6 7 |
/** * Created by macro on 2020/12/9. */ public interface UmsAdminDao { AdminRoleDto selectWithRoleList(@Param("id") Long id); } |
role_前缀;|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<select id="selectWithRoleList" resultMap="AdminRoleResult"> SELECT ua.*, ur.id AS role_id, ur.NAME AS role_name, ur.description AS role_description, ur.create_time AS role_create_time, ur.STATUS AS role_status, ur.sort AS role_sort FROM ums_admin ua LEFT JOIN ums_admin_role_relation uarr ON ua.id = uarr.admin_id LEFT JOIN ums_role ur ON uarr.role_id = ur.id WHERE ua.id = #{id} </select> |
AdminRoleResult的ResultMap,通过collection标签直接将以role_开头的列映射到UmsRole对象中去即可。|
1 2 3 4 5 6 |
<resultMap id="AdminRoleResult" type="com.macro.mall.tiny.domain.AdminRoleDto" extends="com.macro.mall.tiny.mbg.mapper.UmsAdminMapper.BaseResultMap"> <collection property="roleList" resultMap="com.macro.mall.tiny.mbg.mapper.UmsRoleMapper.BaseResultMap" columnPrefix="role_"> </collection> </resultMap> |
一对一查询无法直接使用MBG生成的代码实现,需要手写SQL实现,并使用resultMap来进行结果集映射。
selectResourceWithCate方法;|
1 2 3 4 5 6 7 |
/** * Created by macro on 2020/12/9. */ public interface UmsAdminDao { ResourceWithCateDto selectResourceWithCate(@Param("id")Long id); } |
cate_前缀;|
1 2 3 4 5 6 7 8 9 10 |
<select id="selectResourceWithCate" resultMap="ResourceWithCateResult"> SELECT ur.*, urc.id AS cate_id, urc.`name` AS cate_name, urc.create_time AS cate_create_time, urc.sort AS cate_sort FROM ums_resource ur LEFT JOIN ums_resource_category urc ON ur.category_id = urc.id WHERE ur.id = #{id} </select> |
ResourceWithCateResult的ResultMap,通过association标签直接将以cate_开头的列映射到UmsResourceCategory对象中去即可。|
1 2 3 4 5 6 7 |
<resultMap id="ResourceWithCateResult" type="com.macro.mall.tiny.domain.ResourceWithCateDto" extends="com.macro.mall.tiny.mbg.mapper.UmsResourceMapper.BaseResultMap"> <association property="resourceCategory" resultMap="com.macro.mall.tiny.mbg.mapper.UmsResourceCategoryMapper.BaseResultMap" columnPrefix="cate_"> </association> </resultMap> |
总的来说MyBatis官方代码生成器MBG还是很强大的,可以生成一些常用的单表CRUD方法,减少了我们的工作量。但是对于子查询、多表查询和一些复杂查询支持有点偏弱,依然需要在mapper.xml中手写SQL实现。
官方文档:https://mybatis.org/generator/index.html
from:https://zhuanlan.zhihu.com/p/344147446