idea提供了mybatis-generator插件(代码生成器)
1、新建一个maven项目名为mybatis-generator,文件夹创建mapper及bean和sql映射文件存放地。
2、创建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> <!-- mysql数据源配置文件路径 --> <properties resource="application-dev.yml"/> <context id="DB2Tables" targetRuntime="MyBatis3"> <!--添加这个标签,就证明不会添加注释到代码里面--> <commentGenerator> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--配置数据库连接--> <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${db.url}" userId="${db.username}" password="${db.password}"> <property name="nullCatalogMeansCurrent" value="true"/> </jdbcConnection> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!--指定生成javabean的位置--> <javaModelGenerator targetPackage="com.hnsm.dao" targetProject="src\main\java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!--指定sql的映射文件--> <sqlMapGenerator targetPackage="mapper" targetProject="src\main\resources"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!--指定dao接口生成的位置,mapper接口--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.hnsm.mapper" targetProject="src\main\java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!--table的生成策略--> <!-- <table tableName="ALLTYPES" domainObjectName="Customer" > <property name="useActualColumnNames" value="true"/> <generatedKey column="ID" sqlStatement="DB2" identity="true" /> <columnOverride column="DATE_FIELD" property="startDate" /> <ignoreColumn column="FRED" /> <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> </table> --> <!--可多写 要生成的表名--> <table tableName="books" domainObjectName="Books" ></table> </context> </generatorConfiguration>
3、yml文件配置,主要是用于连接数据库
在generatorConfig.xml文件中设定了数据库连接方法的相关变量如下
<!--配置数据库连接--> <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${db.url}" userId="${db.username}" password="${db.password}"> </jdbcConnection>
所以yml文件中也要与之对应,代码如下
server:
port: 9998
datasource:
mysql:
db.url: jdbc:mysql://127.0.0.1:3306/sqd?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
db.username: root
db.password: ******
jdbc.driver: com.mysql.cj.jdbc.Driver
4、pom配置
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
5、右键点击maven插件运行插件
运行结果如下
6、效果如下: