MyBatis Generator 详细配置 demo
MyBatis Generator 是 MyBatis 提供的一个代码生成工具。可以帮我们生成 表对应的持久化对象(po)、操作数据库的接口(dao)、CRUD sql的xml(mapper)。
MyBatis Generator 是一个独立工具,你可以下载它的jar包来运行、也可以在 Ant 和 maven 运行。
目前已知的代码生成器有两种: MyBatis-Plus 和 MyBatis Generator ;前者是后者的加强版,对于MyBatis-Plus的使用可以参见: MyBatis-Plus 3.4.1 代码生成器 配置demo
0、使用环境
- 开发工具:IDEA
- 数据库:mysql
- 包管理工具:maven
1、配置 MyBatis Generator Config
MyBatis Generator 插件启动后,会根据你在 pom 中配置都路径找到该配置文件。
这个配置文件才是详细都配置 MyBatis Generator 生成代码的各种细节。
其中最重要的就是 context ,你的配置文件至少得包含一个context
-
配置示例:
<?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> <!-- 引入配置文件 --> <properties resource="generator.properties"/> <!-- 一个数据库一个context,context的子元素必须按照它给出的顺序 property*,plugin*,commentGenerator?,jdbcConnection,javaTypeResolver?, javaModelGenerator,sqlMapGenerator?,javaClientGenerator?,table+ --> <context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat"> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> <property name="javaFileEncoding" value="UTF-8"/> <!-- 为模型生成序列化方法--> <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/> <!-- 为生成的Java模型创建一个toString方法 --> <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/> <!-- 注释 --> <!--注释生成配置--> <!--可以自定义生成model的代码注释--> <commentGenerator type="com.macro.mall.tiny.mbg.CommentGenerator"> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true"/> <property name="suppressDate" value="true"/> <property name="addRemarkComments" value="true"/> </commentGenerator> <!--配置数据库连接--> <jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbc.connectionURL}" userId="${jdbc.userId}" password="${jdbc.password}"> <!--解决mysql驱动升级到8.0后不生成指定数据库代码的问题--> <property name="nullCatalogMeansCurrent" value="true" /> </jdbcConnection> <!--实体类配置--> <!--指定生成model的路径--> <javaModelGenerator targetPackage="com.macro.mall.tiny.mbg.model" targetProject="mall-tiny-01\src\main\java"> <property name="enableSubPackages" value="false"/> <property name="trimStrings" value="true"/>