使用maven插件mybatis-generator-maven-plugin自动生成代码,节省很多开发时间。首先在pom文件中引入如下插件:
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<!-- 配置文件及相关配置 -->
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
<dependencies>
<!-- 引入数据库连接依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- 此处是基于tk.mybatis的mapper生成,所以引入依赖 -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-generator</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
</plugin>
在src/main/resources/generator目录下添加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="application.properties"/>
<context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="cn.lovecto.mybatis.mapper.LoveCtoMapper"/>
</plugin>
<!-- 数据库连接配置-->
<jdbcConnection driverClass="${spring.datasource.druid.driver-class-name}"
connectionURL="${spring.datasource.druid.url}"
userId="${spring.datasource.druid.username}"
password="${spring.datasource.druid.password}">
</jdbcConnection>
<!-- 生成模型的位置-->
<javaModelGenerator targetPackage="cn.lovecto.mybatis.model" targetProject="src/main/java"/>
<!-- 生成xml的位置 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>
<!-- 生成接口的位置 -->
<javaClientGenerator targetPackage="cn.lovecto.mybatis.dao.mapper" targetProject="src/main/java" type="XMLMAPPER"/>
<!-- 需要生成的表,要生成多少就写多少 -->
<table tableName="country">
<generatedKey column="Id" sqlStatement="Mysql" identity="true"/>
</table>
</context>
</generatorConfiguration>
generatorConfig.xml配置文件中需要的几项配置是配置在application.properties中的:
spring.datasource.druid.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.url=jdbc:mysql://172.17.0.2:3306/test
spring.datasource.druid.username=root
spring.datasource.druid.password=xxxxxxxxx
数据库表创建好后,右键generatorConfig.xml,Run As -> Run Configuration ->Maven build->New;选中所在的项目,在Goals中输入“mybatis-generator:generate”,再Run,即可生成代码: