# SpringBoot整合Mybatis Generator自动生成的示例分析 ## 1. MyBatis Generator简介 ### 1.1 核心功能概述 MyBatis Generator(简称MBG)是MyBatis官方提供的代码生成工具,能够根据数据库表结构自动生成以下内容: - 实体类(POJO) - Mapper接口 - XML映射文件 - 动态查询条件类(Example类) ### 1.2 典型应用场景 1. **快速开发**:减少70%以上的重复CRUD代码编写 2. **规范统一**:保证项目中的持久层代码风格一致 3. **维护便捷**:表结构变更后重新生成即可同步更新 ## 2. 环境准备 ### 2.1 基础环境要求 | 组件 | 版本要求 | |--------------|---------------| | JDK | 1.8+ | | Spring Boot | 2.3.x+ | | MyBatis | 3.5.0+ | | MySQL | 5.7+ | ### 2.2 Maven依赖配置 ```xml <dependencies> <!-- Spring Boot Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis整合Spring Boot --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <!-- MySQL驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- MyBatis Generator核心 --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.4.1</version> <scope>provided</scope> </dependency> </dependencies>
application.yml
示例:
spring: datasource: url: jdbc:mysql://localhost:3306/mbg_demo?useSSL=false&serverTimezone=UTC username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: com.example.mbg.model
pom.xml
中添加构建插件:
<build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.4.1</version> <configuration> <configurationFile>src/main/resources/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency> </dependencies> </plugin> </plugins> </build>
generatorConfig.xml
完整配置:
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-configuration_1_0.dtd"> <generatorConfiguration> <!-- 数据库驱动路径 --> <classPathEntry location="/path/to/mysql-connector-java-8.0.25.jar"/> <context id="mysqlTables" targetRuntime="MyBatis3"> <!-- 生成的Java文件编码 --> <property name="javaFileEncoding" value="UTF-8"/> <!-- 自动生成注释配置 --> <commentGenerator> <property name="suppressDate" value="true"/> <property name="suppressAllComments" value="false"/> </commentGenerator> <!-- 数据库连接配置 --> <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mbg_demo" userId="root" password="123456"> </jdbcConnection> <!-- Java模型生成配置 --> <javaModelGenerator targetPackage="com.example.mbg.model" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- SQL映射文件生成配置 --> <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- Mapper接口生成配置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mbg.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 表配置 --> <table tableName="user_info" domainObjectName="User"> <generatedKey column="id" sqlStatement="MySQL" identity="true"/> </table> <table tableName="product"> <columnOverride column="price" javaType="java.math.BigDecimal"/> </table> </context> </generatorConfiguration>
targetRuntime:
table元素属性:
<table tableName="%" <!-- 匹配所有表 --> enableCountByExample="false" <!-- 禁用计数查询 --> enableUpdateByExample="false" enableDeleteByExample="false" selectByExampleQueryId="false">
列级自定义:
<table tableName="employee"> <columnOverride column="hire_date" property="hireDate" javaType="java.time.LocalDate"/> <ignoreColumn column="deleted"/> </table>
mvn mybatis-generator:generate
src/ ├── main/ │ ├── java/ │ │ └── com/ │ │ └── example/ │ │ └── mbg/ │ │ ├── model/ # 实体类 │ │ └── mapper/ # Mapper接口 │ └── resources/ │ └── mapper/ # XML映射文件
public class User { private Long id; private String username; private Integer age; private Date createTime; // getters/setters省略 }
public interface UserMapper { int deleteByPrimaryKey(Long id); int insert(User record); User selectByPrimaryKey(Long id); List<User> selectAll(); int updateByPrimaryKey(User record); // 动态条件查询 List<User> selectByExample(UserExample example); int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example); }
<resultMap id="BaseResultMap" type="User"> <id column="id" property="id" jdbcType="BIGINT"/> <result column="username" property="username" jdbcType="VARCHAR"/> <result column="age" property="age" jdbcType="INTEGER"/> </resultMap> <sql id="Example_Where_Clause"> <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> </choose> </foreach> </trim> </if> </foreach> </where> </sql>
实现PluginAdapter
扩展生成逻辑:
public class LombokPlugin extends PluginAdapter { @Override public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { // 添加Lombok注解 topLevelClass.addImportedType("lombok.Data"); topLevelClass.addAnnotation("@Data"); return true; } }
配置使用插件:
<context id="mysqlTables" targetRuntime="MyBatis3"> <plugin type="com.example.plugin.LombokPlugin"/> </context>
// 创建条件对象 UserExample example = new UserExample(); example.createCriteria() .andUsernameLike("%admin%") .andAgeBetween(20, 30) .andCreateTimeGreaterThan(new Date()); // 排序设置 example.setOrderByClause("create_time DESC"); // 执行查询 List<User> users = userMapper.selectByExample(example);
结合PageHelper实现分页:
@GetMapping("/users") public PageInfo<User> getUsers(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize) { PageHelper.startPage(pageNum, pageSize); UserExample example = new UserExample(); example.setOrderByClause("id DESC"); List<User> users = userMapper.selectByExample(example); return new PageInfo<>(users); }
检查数据库连接:
表名大小写问题:
<table tableName="USER_INFO" delimitIdentifiers="true"/>
日志分析:
<context id="mysqlTables"> <property name="logImpl" value="SLF4J"/> </context>
自定义类型转换器:
<table tableName="product"> <columnOverride column="status" javaType="com.example.enums.ProductStatus" typeHandler="org.apache.ibatis.type.EnumOrdinalTypeHandler"/> </table>
部分覆盖策略:
<context id="mysqlTables"> <property name="mergeable" value="true"/> </context>
自定义生成策略:
public class CustomGenerator extends DefaultShellCallback { @Override public boolean isMergeSupported() { return true; } }
启用二级缓存
<cache eviction="LRU" flushInterval="60000"/>
批量操作示例
@Insert("<script>insert into user (username) values " + "<foreach collection='list' item='item' separator=','>(#{item.username})</foreach></script>") void batchInsert(List<User> users);
版本控制策略:
项目目录规范:
src/ ├── generated/ # 生成的代码 ├── main/ # 手动编写的代码 └── resources/ ├── generator/ # MBG配置文件 └── mapper/ # 自定义SQL片段
持续集成集成:
<plugin> <executions> <execution> <id>generate-mybatis</id> <phase>generate-sources</phase> <goals> <goal>generate</goal> </goals> </execution> </executions> </plugin>
通过本文的详细讲解,我们系统性地掌握了Spring Boot与MyBatis Generator的整合方法。合理使用代码生成工具可以显著提升开发效率,但同时需要注意: 1. 生成的代码需要二次审查 2. 复杂查询仍需手动编写SQL 3. 及时更新生成配置保持与数据库同步
建议在实际项目中结合具体需求灵活运用本文介绍的技术方案,打造高效稳定的数据访问层。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。