前言
在Spring项目中,使用Mybatis需要编写dao层接口、mapper文件、PO类,而大多数是为了crud这种很具重复性的操作,使用Mybatis-generator可以自动化部署,解放开发者。
部署Mybatis-generator
-
pom文件中添加插件
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<!-- 在控制台打印执行日志 -->
<verbose>true</verbose>
<!-- 重复生成时会覆盖之前的文件-->
<overwrite>true</overwrite>
<!-- 配置文件 -->
<configurationFile>src/main/resources/mybatis/generatorConfig.xml</configurationFile>
</configuration>
</plugin>
configurationFile
中指定配置文件路径。
-
配置文件
<?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>
<!-- 数据库驱动:换成你本地的驱动包位置-->
<classPathEntry location="D:\maven3.5.4-repo\mysql\mysql-connector-java\8.0.14\mysql-connector-java-8.0.14.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/seckill?characterEncoding=utf8" userId="seckill" password="seckill508225284">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="cn.liaoxiaojie.seckill.entity" targetProject="src/main">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="mybatis.mappers" targetProject="src/main">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="cn.liaoxiaojie.seckill.dao" targetProject="src/main">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要自动化生成的包在下面添加-->
<!-- <table tableName="order" domainObjectName="Order" enableCountByExample="false"-->
<!-- enableUpdateByExample="true" enableDeleteByExample="false" enableSelectByExample="false"-->
<!-- selectByExampleQueryId="true"></table>-->
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="order" domainObjectName="Order" enableCountByExample="false"
enableUpdateByExample="true" enableDeleteByExample="false" enableSelectByExample="true"
selectByExampleQueryId="true"></table>
</context>
</generatorConfiguration>
需要配置的有:
classPathEntry
驱动包位置jdbcConnection
数据库连接信息javaModelGenerator
生成的模型包名和位置sqlMapGenerator
生成映射文件包名和位置javaClientGenerator
生成DAO的包名和位置table
要自动化生成的包(上文指定生成order表的DAO接口、mapper文件、PO类)
运行
双击运行插件,然后查看对应目录生成的文件。