本文介绍了Mybatis官方生成器的基本概念和作用,包括减少重复工作、提高开发效率和保证代码一致性等优势,并详细讲解了安装和配置方法,同时通过示例代码演示了快速上手使用Mybatis官方生成器的步骤。
Mybatis官方生成器简介 什么是Mybatis官方生成器Mybatis官方生成器(Mybatis Generator)是Mybatis官方提供的一个用于自动生成Mybatis相关代码的工具。它可以根据数据库的表结构自动生成POJO(持久化对象)、Mapper接口、Mapper XML文件等代码,从而减少开发人员的手动编码工作量,提高开发效率。
作用
- 减少重复工作:自动生成代码,避免重复手动编写相同的代码。
- 提高开发效率:开发者可以将更多的精力集中在业务逻辑上,减少对持久层代码的维护工作。
- 保证一致性:生成的代码遵循一定的模板和规范,可以保证代码的一致性和可维护性。
- 支持多种数据库:支持多种主流数据库,如MySQL、Oracle、SQL Server等。
优势
- 灵活性:支持自定义模板,可以灵活地调整生成的代码结构和内容。
- 易于集成:可以方便地集成到Maven、Gradle等构建工具中,也可以通过Ant、Ivy等其他构建工具使用。
- 增量更新:支持增量更新,当数据库结构发生变化时,可以只更新发生变化的部分代码。
- 插件支持:支持多种插件,可以方便地扩展功能。
安装
安装Mybatis Generator需要先下载并配置好Java环境。通过Maven或者Gradle等构建工具引入Mybatis Generator的依赖。
Maven
在pom.xml
文件中添加以下依赖:
<dependency>
<groupId>org.mybatis.generator</groupId>
.
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
Gradle
在build.gradle
文件中添加以下依赖:
dependencies {
implementation 'org.mybatis.generator:mybatis-generator-core:1.4.0'
}
配置
配置Mybatis Generator需要编写一个XML配置文件,该文件包含了数据库连接信息、表映射配置等。
配置文件示例
<generatorConfiguration>
<context id="testContext" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test"
userId="root"
password="password">
</jdbcConnection>
<javaModelGenerator targetPackage="com.example.model"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<sqlMapGenerator targetPackage="com.example.mapper"
targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.example.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<table tableName="user"
domainObjectName="User"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
环境配置
确保数据库连接信息正确无误,且数据库中存在相应的表结构。配置完成后,可以通过Maven插件或者直接运行Java代码来执行生成器。
public class MybatisGenerator {
public static void main(String[] args) throws Exception {
List<String> configFiles = Arrays.asList("src/main/resources/mybatis-generator.xml");
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(MyBatisGeneratorBuilder.createConfiguration(configFiles));
myBatisGenerator.generate(null);
}
}
快速上手Mybatis官方生成器
生成器的基本配置
生成器的基本配置主要包含以下几个部分:
- Context:指定了生成器的工作环境,如目标运行时环境(MyBatis3)。
- CommentGenerator:配置注释生成器,可以控制是否生成注释。
- JdbcConnection:配置数据库连接信息,包括驱动类名、连接URL、用户名、密码等。
- JavaModelGenerator:生成持久化对象(POJO)的配置。
- SqlMapGenerator:生成Mapper XML文件的配置。
- JavaClientGenerator:生成Mapper接口的配置。
- Table:配置需要生成代码的数据库表信息。
示例代码
<generatorConfiguration>
<context id="testContext" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test"
userId="root"
password="password">
</jdbcConnection>
<javaModelGenerator targetPackage="com.example.model"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<sqlMapGenerator targetPackage="com.example.mapper"
targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.example.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<table tableName="user"
domainObjectName="User"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
创建第一个生成器项目
-
创建项目结构
创建一个标准的Java项目结构:
mybatis-generator-demo/ ├── src/main/java │ └── com/example │ └── MybatisGenerator.java ├── src/main/resources │ └── mybatis-generator.xml
-
编写配置文件
在
src/main/resources
目录下创建mybatis-generator.xml
配置文件,并添加基本配置。 -
编写Java启动类
在
src/main/java
目录下创建启动类MybatisGenerator.java
,用于启动生成器。package com.example; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.MasterConfigurationBuilder; import org.mybatis.generator.config.MasterConfigurationBuilderParameters; import org.mybatis.generator.config.MasterConfigurationBuilderParametersBuilder; import java.util.Arrays; public class MybatisGenerator { public static void main(String[] args) throws Exception { List<String> configFiles = Arrays.asList("src/main/resources/mybatis-generator.xml"); MyBatisGenerator myBatisGenerator = new MyBatisGenerator( MasterConfigurationBuilder.createConfiguration( MasterConfigurationBuilderParameters.builder() .withConfigFiles(configFiles) .build() ) ); myBatisGenerator.generate(null); } }
-
编译并运行
编译项目并运行
MybatisGenerator
类,生成器将根据配置生成相应的代码。
生成器的基本使用
生成器生成的代码将按照配置文件中的设置放置在指定的目录下。常见的代码结构如下:
- POJO
package com.example.model;
public class User {
private String id;
private String name;
// Getter and Setter
}
- **Mapper XML**
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.model.User">
<id column="id" property="id" />
<result column="name" property="name" />
</resultMap>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String">
SELECT `id`, `name` FROM `user` WHERE `id` = #{id}
</select>
</mapper>
- Mapper接口
package com.example.mapper;
import com.example.model.User;
public interface UserMapper {
User selectByPrimaryKey(String id);
}
# Mybatis官方生成器的常用配置
## 数据库连接和表映射配置
数据库连接和表映射配置是最基础的配置,决定了生成器如何连接数据库和从哪些表生成代码。
### 数据库连接配置
```xml
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test"
userId="root"
password="password">
</jdbcConnection>
表映射配置
<table tableName="user"
domainObjectName="User"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
自动生成的代码结构解析
生成的代码通常包含以下几个部分:
- POJO:持久化对象,如
User.java
。 - Mapper XML:包含SQL语句的XML文件,如
UserMapper.xml
。 - Mapper接口:定义了数据访问操作的接口,如
UserMapper.java
。
插件和拓展配置
生成器支持插件,可以通过插件来扩展其功能,如添加自定义的生成逻辑。
示例插件配置
<plugin type="com.example.MybatisGeneratorPlugin">
<property name="param" value="value"/>
</plugin>
插件实现示例
package com.example;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
public class MybatisGeneratorPlugin extends PluginAdapter {
@Override
public boolean validate(List<String> warnings) {
return true;
}
@Override
public boolean sqlMapInsertSelectiveElementGenerated(String insertSelectiveElement, IntrospectedTable introspectedTable) {
System.out.println("InsertSelective element generated for table " + introspectedTable.getFullyQualifiedTable());
return super.sqlMapInsertSelectiveElementGenerated(insertSelectiveElement, introspectedTable);
}
}
自定义模板和结果映射
自定义模板
可以通过自定义模板来生成特定格式的代码。模板文件通常放在src/main/resources
目录下,并通过配置文件指定。
模板配置示例
<javaModelGenerator targetPackage="com.example.model"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
<property name="eclipseFormatterFile" value="myformatter.xml"/>
<property name="templateLocation" value="src/main/resources/templates"/>
</javaModelGenerator>
模板文件示例
package ${package};
public class ${simpleClassName} {
private ${type} ${property};
// Getter
public ${type} get${property}() {
return ${property};
}
// Setter
public void set${property}(${type} ${property}) {
this.${property} = ${property};
}
}
结果映射
结果映射定义了如何将数据库表中的字段映射到Java对象的属性。
结果映射配置示例
<resultMap id="baseResultMap" type="com.example.model.User">
<id column="id" property="id" />
<result column="name" property="name" />
</resultMap>
生成器的批量处理和增量更新
批量处理
生成器可以通过配置文件中的<table>
标签来指定需要生成代码的表。
示例配置
<table tableName="user"
domainObjectName="User"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
增量更新
增量更新功能允许在数据库表结构发生变化时,只更新发生变化的部分代码。
增量更新配置
<databaseChangeLog>
<changeSet id="1" author="author">
<addColumn tableName="user">
<column name="email" type="VARCHAR(255)"/>
</addColumn>
</changeSet>
</databaseChangeLog>
动态SQL生成
动态SQL生成功能可以根据不同的条件生成不同的SQL语句。
示例配置
<select id="selectByCondition" parameterType="map" resultType="com.example.model.User">
SELECT * FROM user
<if test="name != null">
WHERE name = #{name}
</if>
<if test="email != null">
AND email = #{email}
</if>
</select>
使用Mybatis官方生成器的最佳实践
避免常见的配置陷阱
配置文件路径问题
确保配置文件路径正确,避免因路径问题导致生成失败。
数据库连接信息错误
确保数据库连接信息配置正确,包括驱动类名、连接URL、用户名、密码等。
表映射配置错误
确保表映射配置中的表名、列名等信息与数据库中的实际信息一致。
生成器性能优化建议缓存机制
利用缓存机制减少重复生成代码的时间。
并发生成
通过并发生成减少生成时间。
自动化构建流程集成Maven集成
在Maven项目中,可以使用Maven插件来执行生成器。
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.0</version>
<configuration>
<configurationFile>src/main/resources/mybatis-generator.xml</configurationFile>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
Gradle集成
在Gradle项目中,可以使用Gradle插件来执行生成器。
apply plugin: 'mybatis-generator'
mybatisGenerator {
configurationFile = 'src/main/resources/mybatis-generator.xml'
overwrite = true
}
dependencies {
mybatisGenerator 'mysql:mysql-connector-java:8.0.23'
}
常见问题及解决方案
常见的错误提示及解决方法
错误1:找不到数据库连接
确保数据库连接信息配置正确,且数据库服务正常运行。
错误2:表不存在
检查配置文件中的表名是否正确,确保数据库中存在相应的表。
错误3:生成代码错误
检查配置文件中的模板和结果映射配置是否正确。
与其他框架集成时的注意事项Spring集成
在Spring项目中,确保生成的Mapper接口和Mapper XML文件能够被Spring正确扫描和注入。
Spring Boot集成
在Spring Boot项目中,可以通过配置mybatis
相关属性来自动扫描生成的Mapper接口和Mapper XML文件。
通过以上内容,希望能帮助你更好地理解和使用Mybatis官方生成器,提高开发效率。
共同學習,寫下你的評論
評論加載中...
作者其他優質文章