MyBatis简单易用,但是需要编写大量的实体类、Mapper接口和Mapper映射文件。
我们可以使用 Mybatis-Generator 来帮助我们完成以上文件的自动生成。
下载 Mybatis-Generator
https://github.com/mybatis/generator
此外,我们还需要数据库驱动文件,接下来的演示以mysql数据库为例。
编写配置文件 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="jdbc.properties"/>-->
<!-- !!!! Driver Class Path !!!! -->
<classPathEntry location="mysql-connector-java-5.1.40.jar"/>
<context id="context" targetRuntime="MyBatis3">
<property name="javaFileEncoding" value="UTF-8"/>
<commentGenerator>
<property name="suppressAllComments" value="true"/>
<property name="suppressDate" value="true"/>
</commentGenerator>
<!-- !!!! Database Configurations !!!! -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=true" userId="root" password="lgh123"/>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- !!!! Model Configurations !!!! -->
<javaModelGenerator targetPackage="cn.bjut.entity" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- !!!! Mapper XML Configurations !!!! -->
<sqlMapGenerator targetPackage="cn.bjut.mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- !!!! Mapper Interface Configurations !!!! -->
<javaClientGenerator targetPackage="cn.bjut.mapper" targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- !!!! Table Configurations !!!! -->
<table tableName="persons" domainObjectName="Person" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
enableUpdateByExample="false" />
</context>
</generatorConfiguration>
tableName和domainObjectName分别代表数据库表名和生成的实体类名。
<properties url="file:///D:/N3verL4nd/Desktop/M/src/main/resources/jdbc.properties"/>
<!-- !!!! Database Configurations !!!! --> <jdbcConnection driverClass="${jdbc.driverClassName}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
可以如上加载数据库配置文件,貌似使用resource不能使用。
测试脚本(Windows):
@echo off
if exist src rd /S /Q src
mkdir src\main\java
mkdir src\main\resources
java -jar mybatis-generator-core-1.3.5.jar -configfile generatorConfig.xml
pause
详细参数可查看:http://www.mybatis.org/generator/running/runningFromCmdLine.html