项目刚启动时,会有好多表需要编写实体类,mapper接口和映射文件,这些其实没有技术含量,那么我们就要想办法偷个懒,提高我们的工作效率,现在介绍的就是使用mybatics自动生成,不需要我们手写,当然前提是项目使用的框架就是mybatics。
在pom.xml文件中引入mybatics生成插件:
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
同时由于后面代码运行需要,引入ant依赖:
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.10.1</version>
</dependency>
写个配置文件generateConfig.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>
<!-- ORACLE的jar包路径 -->
<classPathEntry location="libs/ojdbc6.jar" />
<context id="oracle_tables" targetRuntime="MyBatis3">
<!-- 配置实体类不要出现注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
<property name="suppressDate" value="true" />
</commentGenerator>
<!-- 数据库连接信息 -->
<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
connectionURL="jdbc:oracle:thin:@localhost:1521/testing"
userId="test"
password="test">
</jdbcConnection>
<!-- 将数值类型强制转换为BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject为实体类存放路径 -->
<javaModelGenerator
targetPackage="com.demo.test.entity"
targetProject="src\main\java">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- mapper配置文件存放路径 -->
<sqlMapGenerator
targetPackage="mapper.base"
targetProject="src\main\resources">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- mapper接口存放路径 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.demo.test.mapper.base"
targetProject="src\main\java">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 数据库表配置,tableName写表名,domainObjectName为实体类对象名称,其他不用变,多个表对应多个table标签 -->
<table schema="" tableName="INSURANCE_AGREEMENT" domainObjectName="InsuranceAgreement"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
写个MybatisGeneratorUtil工具类:
package com.demo.test.utils;
import org.mybatis.generator.ant.GeneratorAntTask;
public class MybatisGeneratorUtil {
public static void main(String[] args) {
// filePath指向generatorConfig.xml配置文件
String filePath = "src/main/resources/builder/generatorConfig.xml";
GeneratorAntTask task = new GeneratorAntTask();
task.setConfigfile(filePath);
task.execute();
System.out.println("mapper创建完毕");
}
}
有了上面这些配置,现在就直接运行MybatisGeneratorUtil类吧!