springboot如何集成mybatis官方生成器

发布时间:2022-03-04 11:06:14 作者:小新
来源:亿速云 阅读:195
# SpringBoot如何集成MyBatis官方生成器

## 一、前言

在现代Java企业级应用开发中,SpringBoot和MyBatis的组合因其高效、灵活的特性被广泛采用。MyBatis官方提供的代码生成器(MyBatis Generator,简称MBG)能够自动生成实体类、Mapper接口和XML映射文件,显著提升开发效率。本文将详细介绍如何在SpringBoot项目中集成MyBatis官方生成器。

## 二、环境准备

### 1. 基础环境要求
- JDK 1.8+
- Maven 3.6+ 或 Gradle 6.x+
- SpringBoot 2.5+(本文以2.7.0为例)
- MyBatis 3.5+

### 2. 创建SpringBoot项目
使用Spring Initializr创建项目时需勾选:
- Spring Web
- MyBatis Framework
- MySQL Driver(或其他数据库驱动)

或通过命令创建:
```bash
mvn archetype:generate -DgroupId=com.example -DartifactId=mybatis-demo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

三、MyBatis Generator核心配置

1. 添加Maven依赖

在pom.xml中添加MBG插件和数据库驱动:

<build>
    <plugins>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.4.1</version>
            <dependencies>
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>8.0.28</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

2. 配置文件generatorConfig.xml

在src/main/resources下创建配置文件:

<?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="/path/to/mysql-connector-java.jar"/>
    
    <context id="MySQLTables" targetRuntime="MyBatis3">
        <!-- 生成的Java文件编码 -->
        <property name="javaFileEncoding" value="UTF-8"/>
        
        <!-- 注释配置 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        
        <!-- 数据库连接配置 -->
        <jdbcConnection 
            driverClass="com.mysql.cj.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/test"
            userId="root"
            password="123456">
        </jdbcConnection>
        
        <!-- Java模型生成器 -->
        <javaModelGenerator 
            targetPackage="com.example.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.mapper"
            targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        
        <!-- 指定要生成的表 -->
        <table tableName="user" domainObjectName="User"/>
    </context>
</generatorConfiguration>

四、SpringBoot集成配置

1. 配置数据源

application.yml配置示例:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useSSL=false
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

2. 添加MyBatis配置

@Configuration
@MapperScan("com.example.mapper")
public class MyBatisConfig {
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        // 配置XML文件位置
        sessionFactory.setMapperLocations(
            new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/*.xml"));
        return sessionFactory.getObject();
    }
}

五、代码生成与使用

1. 执行生成命令

通过Maven命令执行生成:

mvn mybatis-generator:generate

或配置自动生成:

<plugin>
    <executions>
        <execution>
            <id>Generate MyBatis Artifacts</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>

2. 生成文件结构

生成成功后项目中将出现:

src/
├── main/
│   ├── java/
│   │   └── com/example/
│   │       ├── model/User.java
│   │       └── mapper/UserMapper.java
│   └── resources/
│       └── mapper/UserMapper.xml

3. 使用生成的Mapper

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    
    public User getUserById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }
}

六、高级配置技巧

1. 自定义类型转换器

<context id="MySQLTables" targetRuntime="MyBatis3">
    <javaTypeResolver>
        <property name="forceBigDecimals" value="true"/>
    </javaTypeResolver>
</context>

2. 生成Example类

<table tableName="user" domainObjectName="User"
       enableCountByExample="true"
       enableUpdateByExample="true"
       enableDeleteByExample="true"
       enableSelectByExample="true"
       selectByExampleQueryId="true"/>

3. 自定义插件开发

实现Plugin接口:

public class CustomPlugin extends PluginAdapter {
    @Override
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, 
            IntrospectedTable introspectedTable) {
        // 添加自定义注解
        topLevelClass.addAnnotation("@lombok.Data");
        return true;
    }
}

七、常见问题解决

1. 生成器执行失败排查

2. 与Lombok集成

添加Lombok依赖后,在generatorConfig.xml中配置:

<commentGenerator>
    <property name="suppressAllComments" value="true"/>
</commentGenerator>

3. 多模块项目配置

对于Maven多模块项目,需指定正确的targetProject路径:

<javaModelGenerator 
    targetPackage="com.example.model"
    targetProject="${project.basedir}/core/src/main/java">

八、最佳实践建议

  1. 版本控制:生成的文件建议加入.gitignore,避免频繁冲突
  2. 定制模板:通过修改MyBatis Generator源码或使用Velocity模板实现个性化生成
  3. 增量生成:使用标签的override属性控制文件覆盖策略
  4. 多环境支持:通过Maven Profile区分不同环境的数据库配置
  5. 九、总结

    通过本文的详细步骤,我们实现了: 1. SpringBoot与MyBatis Generator的无缝集成 2. 自动化生成实体类、Mapper接口和XML文件 3. 高级定制化配置的实现 4. 常见问题的解决方案

    MyBatis Generator的强大功能可以节省约30%的重复编码时间,特别适合中大型项目的快速开发。建议结合具体业务需求,灵活运用各种配置选项,最大化提升开发效率。

    注意:本文示例基于MySQL数据库,其他数据库只需更换驱动和连接配置即可适配。实际项目请根据具体情况调整参数。 “`

    (全文约2950字)

    免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

    您好,登录后才能下订单哦!

    密码登录
    登录注册
    其他方式登录
    点击 登录注册 即表示同意《亿速云用户服务条款》