MyBatis-Generator
MyBatis-Generator (MBG) 是一个 MyBatis 的代码生成器,它可以根据数据库表结构生成 MyBatis 的代码,包括数据访问对象(DAO)、数据模型(实体类)和 MyBatis 映射文件。
Maven安装
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.2</version>
</dependency>
运行生成器
1. 通过Maven Plugin
2. 通过Java
public class MyMyBatisGenerator {
public static void main(String[] args) throws Exception{
ArrayList<String> warnings = new ArrayList<>();
boolean overwrite = true;
ConfigurationParser configurationParser = new ConfigurationParser(warnings);
InputStream configResource = MyMyBatisGenerator.class.getResourceAsStream("generatorConfig.xml");
// 解析配置文件
Configuration configuration = configurationParser.parseConfiguration(configResource);
// 设置回调
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(configuration, callback, warnings);
// 启动生成器
myBatisGenerator.generate(null);
}
}
Mybatis Generator 配置文件
Mybatis Generator(MBG)由xml配置文件驱动。配置文件告诉MBG:
- 如何连接数据库
- 生成什么对象以及如何生成它们
- 应该使用哪些表来生成对象
<classPathEntry> (可选)
<classPathEntry> 元素将类路径位置添加到MBG运行的类路径中。MBG在以下情况从这些位置加载类:
- 加载JDBC驱动程序进行数据库自检
- 在JavaModelGenerator中加载根类以检查重写方法时
示例:
<classPathEntry location="file location dir"/>
<properties>
<properties> 元素用于指定用于解析配置的外部属性文件。配置中的任何属性都将接受以下形式的属性${property}。将在指定的properties文件中搜索匹配值,并替换匹配值。属性文件具有 Java Properties文件的正常格式
示例:
<properties resource="generator.properties"></properties>
<context>
<context> 元素用于指定生成一组对象的环境。子元素用于指定要连接的数据库、要生成的对象类型以及要使用的表。可以在<generatorConfiguration>元素内列出多个 <context> 元素,以便在 MyBatis Generator (MBG) 的同一次运行中从不同的数据库或使用不同的生成参数生成对象。
必填属性
id:<context>在配置文件中唯一标识
可选属性
defaultModelType:用于指定生成的 Java 模型的默认类型。MBG 支持以下三种模型类型:- conditional: 生成的模型类包含字段、getter 和 setter 方法,还包含 example 类(用于条件查询)。
- flat: 生成的模型类仅包含字段、getter 和 setter 方法,不生成 example 类。
- hierarchical: 生成的模型类包含字段、getter 和 setter 方法,每个表生成一个独立的模型类,还生成一个用于条件查询的 example 类。
targetRuntime:用于指定生成的代码与 MyBatis 的哪个版本或哪种特定框架兼容。- MyBatis3:生成与 MyBatis 3.x 兼容的代码。
- MyBatis3Simple:生成与 MyBatis 3.x 兼容的简化代码,不包含
example类。 - MyBatis3Kotlin:生成与 MyBatis 3.x 兼容的 Kotlin 代码。
- Ibator:生成与 MyBatis 1.x 兼容的代码。
支持的属性
| 属性名 | 是否必填 | 属性值 | 解释 |
|---|---|---|---|
| autoDelimitKeywords | 否 | ture 或false | 指定是否自动为关键字添加分隔符。假设数据库中有一个名为 user 的表,而 user 是 MySQL 的一个保留字。通过设置 autoDelimitKeywords="true",MBG 会自动在生成的 SQL 中为 user 添加分隔符,使其变成 user。这样,生成的 SQL 就不会因为表名或列名是保留字而导致错误。 |
| beginningDelimiter | 否 | 字符 | 指定数据库表和列名的起始分隔符。例如` |
| endingDelimiter | 否 | 字符 | 指定数据库表和列名的结束分隔符。例如` |
| javaFileEncoding | 否 | 文件编码格式 | 指定生成的 Java 文件的编码。 |
| javaFormatter | 否 | 类路径 | 指定用于格式化生成的 Java 代码的类。 |
| xmlFormatter | 否 | 类路径 | 指定用于格式化生成的 XML 代码的类。 |
property
property 元素用于设置各种配置选项和属性
<jdbcConnection>
jdbcConnection 元素用于配置连接数据库所需的 JDBC 连接信息。
必填属性
- driverClass:数据库驱动类的完全限定名(必需)。
- connectionURL:数据库的连接 URL(必需)。
可选属性
- userId:连接数据库的用户名(可选)。
- password:连接数据库的密码(可选)。
示例:
<jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"></jdbcConnection>
commentGenerator
commentGenerator 元素用于配置生成代码时的注释生成器。注释生成器可以在生成的 Java 类、字段、方法和 SQL 映射文件中添加注释
可选属性
- type:设置自定义注释生成器。自定义注释生成器需要实现
org.mybatis.generator.api.CommentGenerator接口。
支持属性
- suppressDate:是否在生成的注释中抑制日期信息。值为
true或false。 - suppressAllComments:是否抑制所有的注释。值为
true或false。 - addRemarkComments:是否为数据库表的每一列生成注释(从数据库的列备注中提取)。值为
true或false。
示例:
<commentGenerator type="com.gaoj.generate.mybatis.generator.MyCommentGenerator">
<property name="author" value="${profile.author}"/>
</commentGenerator>
public class MyCommentGenerator extends EmptyGenerator {
private Properties properties;
public MyCommentGenerator() {
properties = new Properties();
}
@Override
public void addConfigurationProperties(Properties properties) {
// 获取到配置文件中的配置
this.properties.putAll(properties);
}
/**
* model层仓储类注释
* @param topLevelClass
* @param introspectedTable
*/
@Override
public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
String author = properties.getProperty("author");
String tableRemarks = introspectedTable.getRemarks();
topLevelClass.addJavaDocLine("/**");
topLevelClass.addJavaDocLine("* @author " + author);
topLevelClass.addJavaDocLine("* @description: 【" + tableRemarks + "】实体类");
topLevelClass.addJavaDocLine("* @date " + TimeUtil.getDateStr());
topLevelClass.addJavaDocLine("*/");
}
@Override
public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
String author = properties.getProperty("author");
method.addJavaDocLine("/**");
method.addJavaDocLine("* @author " + author);
method.addJavaDocLine("* @description: " + method.getName() + " " + introspectedTable.getRemarks());
method.addJavaDocLine("* @date " + TimeUtil.getDateStr());
method.addJavaDocLine("*/");
}
/**
* 类属性添加注释
* @param field
* @param introspectedTable
* @param introspectedColumn
*/
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
field.addJavaDocLine("/**");
field.addJavaDocLine("* " + introspectedColumn.getRemarks());
field.addJavaDocLine("*/");
}
}
javaTypeResolver
javaTypeResolver 元素用于配置 Java 类型解析器,它用于将数据库中的数据类型映射到 Java 类型。该类必须实现接口 org.mybatis.generator.api.JavaTypeResolver,并且必须具有公共默认构造函数。该属性还接受特殊值 DEFAULT,在这种情况下将使用默认实现(这与不指定类型具有相同的效果)。
支持的属性
- forceBigDecimals:用于强制将数据库中的
DECIMAL和NUMERIC类型映射为 Java 的BigDecimal类型。
示例
<javaTypeResolver type="com.gaoj.mbg.resolver.MyJavaTypeResolver">
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
public class MyJavaTypeResolver extends JavaTypeResolverDefaultImpl {
public MyJavaTypeResolver() {
super();
// 将tinyint映射为integer类型
super.typeMap.put(Types.TINYINT,new JdbcTypeInformation("TINYINT",new FullyQualifiedJavaType(Integer.class.getName())));
}
}
javaModelGenerator
javaModelGenerator 元素用于配置 Java 模型类的生成行为。Java 模型生成器会构建与自检表匹配的主键类、记录类和按示例查询类。<context>元素必需子元素。
支持属性
-
constructorBased:是否为类生成一个构造函数,该构造函数接受类中每个字段的值。此外,将构建 SQL 结果映射以使用构造函数而不是每个字段的“setter”。
-
immutable:是否生成不可变的模型类 - 这意味着这些类将没有“setter”方法,并且构造函数将接受类中每个字段的值。
-
targetPackage:指定生成的模型类的包名。
-
targetProject:指定生成的模型类的目标项目目录。
-
enableSubPackages:是否启用子包。如果设置为
true,则会根据表名生成子包。 -
trimStrings:是否修剪字符串。如果设置为
true,则会自动修剪字符串字段中的空格。
示例:
<!-- 生成数据库对应的model实体-->
<javaModelGenerator targetPackage="${entity.package}" targetProject="${entity.project}">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
sqlMapGenerator
sqlMapGenerator用于配置 SQL 映射文件的生成行为。它控制生成的 SQL 映射文件的位置和包名。
必填的属性
- targetPackage:指定生成映射文件的包名
- targetProject:指定生成映射文件的项目名
支持的属性
- enableSubPackages:是否启用子包。如果设置为
true,则会根据表名生成子包。
示例
<sqlMapGenerator targetPackage="${mapper.package}" targetProject="${mapper.project}">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
javaClientGererator
<javaClientGenerator> 元素用于定义 Java 客户端生成器的属性
必填属性
- type:选择预定义的 Java 客户端生成器之一,或指定用户提供的 Java 客户端生成器。任何用户提供的生成器都必须扩展类
org.mybatis.generator.codegen.AbstractJavaClientGenerator,并且必须具有公共默认构造函数。提供下列选项- ANNOTATEDMAPPER:生成的对象将是 MyBatis 3.x 映射器基础架构的 Java 接口。这些接口将基于注释和 MyBatis 3.x SqlProviders。不会生成任何 XML 映射器文件。
- MIXEDMAPPER:生成的对象将是 MyBatis 3.x 映射器基础架构的 Java 接口。接口将基于注释和 XML 的混合。
- XMLMAPPER:生成的对象将是 MyBatis 3.x 映射器基础架构的 Java 接口。接口将依赖于生成的 XML 映射器文件。
支持的属性
- enableSubPackages:是否启用子包。如果设置为
true,则会根据表名生成子包。
示例:
<javaClientGenerator type="XMLMAPPER" targetPackage="${dao.package}" targetProject="${dao.project}">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
table
table用于指定要生成代码的数据库表。
必填属性
- tableName:数据库表的名称
可选属性
- schema:表所在的数据库模式。通常在使用支持模式的数据库(如 PostgreSQL 和 Oracle)时使用。
- catalog:表所在的数据库目录。通常在使用支持目录的数据库(如 MySQL)时使用。
- domainObjectName:生成的 Java 类的名称。如果不指定,默认会根据表名生成类名。
- mapperName:生成映射文件Mapper和xml文件的名称。如果未指定,则名称是domainObjectName名称加上
Mapper - enableInsert:是否生成插入语句。默认为
true。 - enableSelectByPrimaryKey:是否生成根据主键选择的语句。默认为
true。 - enableSelectByExample:是否生成根据示例选择的语句。默认为
true。 - enableUpdateByPrimaryKey:是否生成根据主键更新的语句。默认为
true。 - enableUpdateByExample:是否生成根据示例更新的语句。默认为
true。 - enableDeleteByPrimaryKey:是否生成根据主键删除的语句。默认为
true。 - enableDeleteByExample:是否生成根据示例删除的语句。默认为
true。 - enableCountByExample:是否生成计数语句。默认为
true。 - selectByPrimaryKeyQueryId:自定义查询ID,用于根据主键选择。
- selectByExampleQueryId:自定义查询ID,用于根据示例选择。
- modelType:生成的模型类的类型。默认值为
conditional。其他可选值包括flat和hierarchical。
支持的属性
- constructorBased:用于指定生成的模型类是否应使用构造函数来初始化其字段
- immutable:生成类将没有“setter”方法,构造函数将接受类中每个字段的值。
- modelOnly:是否仅为表生成模型类。
- trimStrings:是否修剪字符串
- useActualColumnNames:如果为 true,则 MBG 将使用从数据库元数据返回的列名作为生成的域对象的属性。如果为 false(默认),则 MBG 将尝试对返回的名称进行驼峰式命名。
- useColumnIndexes:用于指定是否使用列的索引而不是列名来引用数据库表的列。默认值
false
- useColumnIndexes:用于指定是否使用列的索引而不是列名来引用数据库表的列。默认值
- useCompoundPropertyNames:如果为 true,则 MBG 将使用将列名与列注释连接起来来生成属性名称。
示例:
<table tableName="Student" domainObjectName="StudentEntity"
enableSelectByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableCountByExample="false" selectByExampleQueryId="false">
<property name="useActualColumnNames" value="false"/>
</table>
plugin
<plugin> 元素用于定义插件。插件可用于扩展或修改 MyBatis Generator (MBG) 生成的代码。
必填属性
- type:实现插件的类的完全限定名称。该类必须实现接口
org.mybatis.generator.api.Plugin,并且必须具有公共默认构造函数。请注意,扩展适配器类比org.mybatis.generator.api.PluginAdapter实现整个接口要容易得多。
示例
<plugin type="com.gaoj.generate.mybatis.plugin.CustomMapperXmlPlugin">
<property name="endName" value="Dao"/>
<property name="tablePrefix" value="tb_"/>
<property name="author" value="${profile.author}"/>
<property name="servicePackage" value="${service.package}"/>
</plugin>