首页 > 文章列表 > 深入解析MyBatis Generator配置并指导如何使用

深入解析MyBatis Generator配置并指导如何使用

配置 mybatis
431 2024-02-21

MyBatis Generator是一个强大的代码生成工具,可以帮助开发人员自动生成与数据库表对应的Java Bean、Mapper接口和XML文件。本文将详细介绍如何配置和使用MyBatis Generator,并提供具体的代码示例,帮助读者快速上手该工具。

一、配置MyBatis Generator

  1. 在项目的pom.xml文件中添加MyBatis Generator依赖:

    <dependency>
     <groupId>org.mybatis.generator</groupId>
     <artifactId>mybatis-generator-core</artifactId>
     <version>1.4.0</version>
    </dependency>
  2. 创建MyBatis Generator的配置文件(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>
     <context id="MyBatisGenerator" targetRuntime="MyBatis3">
         <commentGenerator>
             <property name="suppressDate" value="true"/>
             <property name="suppressAllComments" value="true"/>
         </commentGenerator>
    
         <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                         connectionURL="jdbc:mysql://localhost:3306/test"
                         userId="root"
                         password="password"/>
         
         <javaModelGenerator targetPackage="com.example.model"
                             targetProject="src/main/java"/>
    
         <sqlMapGenerator targetPackage="mapper"
                           targetProject="src/main/resources"/>
    
         <javaClientGenerator type="XMLMAPPER"
                               targetPackage="com.example.mapper"
                               targetProject="src/main/java"/>
    
         <table tableName="user" domainObjectName="User"/>
    
     </context>
    </generatorConfiguration>
  3. 配置Maven插件,执行MyBatis Generator:

    <plugin>
     <groupId>org.mybatis.generator</groupId>
     <artifactId>mybatis-generator-maven-plugin</artifactId>
     <version>1.4.0</version>
     <configuration>
         <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
         <overwrite>true</overwrite>
         <verbose>true</verbose>
     </configuration>
    </plugin>

二、使用MyBatis Generator

  1. 运行Maven插件生成代码:
    在项目根目录执行以下命令:

    mvn mybatis-generator:generate
  2. 自动生成的文件结构如下:
  3. src/main/java/com/example/model/User.java
  4. src/main/resources/mapper/UserMapper.xml
  5. src/main/java/com/example/mapper/UserMapper.java
  6. 使用生成的Mapper接口:

    // 自动注入生成的Mapper接口
    @Autowired
    private UserMapper userMapper;
    
    // 调用Mapper接口方法
    User user = new User();
    user.setId(1);
    user.setName("Test");
    userMapper.insert(user);

通过以上配置和使用方法,开发人员可以快速生成并使用MyBatis对应的Java Bean、Mapper接口和XML文件,提高开发效率并降低重复劳动。希望本文对读者理解和使用MyBatis Generator有所帮助。