一、MGB(MyBatis Generator)代码生成器
在Mybatis中,对于单表操作,其实都是一个类似的重复操作,Mybatis提供了代码生成器,用于生成Mybatis的mapper接口和mapper.xml文件以及对应的实体类。
二、使用教程
1.添加插件到maven
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
2.创建并设置好配置文件
在resources目录下创建一个名为: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>
<!-- 引入配置文件 -->
<!-- <properties resource="" />-->
<!--配置要链接的数据库的数据源,如果是Mysql则只能使用6.0版本以下的-->
<classPathEntry location="D:/apache-maven-3.6.1/local_repository/mysql/mysql-connector-java/5.1.46/mysql-connector-java-5.1.46.jar" />
<!---Mybatis上下文-->
<context id="context1" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 配置数据库连接 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis_study?serverTimezone=GMT%2B8"
userId="root" password="123456" />
<!--数据库BigDecimals字段在java中定义,如果设置为true,则是一定转换为BigDecimals,否则看情况自动转换 -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!--实体类生成信息-->
<javaModelGenerator targetPackage="com.my.entity"
targetProject="src/main/java" />
<!--mybatis 的xml文件地址-->
<sqlMapGenerator targetPackage="." targetProject="src/main/resources/mappers" />
<!--mybatis的mapper接口-->
<javaClientGenerator targetPackage="com.my.mapper"
targetProject="src/main/java" type="XMLMAPPER" />
<!--要生成的表结构1-->
<table tableName="person" domainObjectName="Person"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
<!--要生成的表结构2-->
<!-- <table tableName="person" domainObjectName="Person"-->
<!-- enableCountByExample="false" enableUpdateByExample="false"-->
<!-- enableDeleteByExample="false" enableSelectByExample="false"-->
<!-- selectByExampleQueryId="false">-->
<!-- </table>-->
</context>
</generatorConfiguration>
3.执行maven命令
配置完毕后,需要执行maven命令运行:mvn mybatis-generator:generate
运行之后就会生成对应的代码,主要是mapper接口,mapper映射文件以及实体类。
三、补充说明
1.如果使用的是Mysql,则classPathEntry设置数据库的驱动源必须是6.0版本一下,否则会报错。
2.可以一次性生成多个表格的,只需要在table标签后继续添加table标签即可
3.对于该配置文件,必须要按照严格的顺序,否则会报错,最好在模板之上进行内容修改
4.一般都是通过properties引入外部配置文件,方便内容的修改,然后通过表达式${}引入外部配置文件的内容,此处为了直观并没有引入。