本文转自:http://useky.blog.sohu.com/236585331.html
以前用ibatis,总觉的手工建实体类和mapper.xml很烦,所幸发现了ibator/abator,不仅可以自动生成实体和sqlMap,连带着DAO也一起生成出来了,还对每一个实体有一个Example类,用来把查询条体也对象化了,用起来十分的爽。
最近这个项目要改用MyBatis,结果ibator/abator不能用了,上网查了半天,总算找到了mybatis-generator,能达到相似的功能。这是个maven的插件,只需在pom.xml的build-plugin节点下加上如下配置:
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.1</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
这个需要有一个配置文件generatorConfig.xml,默认扔在src/main/resouces下就好了。内容如下:
<?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">
<!-- org.mybatis.generator:mybatis-generator-maven-plugin:1.3.1:generate -->
<generatorConfiguration>
<!-- 这里填个数据库连接器的jar包位置-->
<classPathEntry location="E:\Dev\repo\mysql\mysql-connector-java\5.1.17\mysql-connector-java-5.1.17.jar" />
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true" />
</commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://?.?.?.?:????/datebase?useUnicode=true&characterEncoding=UTF-8" userId="user" password="password">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<javaModelGenerator targetPackage="test.model"
targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<sqlMapGenerator targetPackage="test.dao"
targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER"
targetPackage="test.dao" targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<table tableName="student" domainObjectName="Student">
</table>
</context>
</generatorConfiguration>
然后就是执行命令了:mvn mybatis-generator:generate 。如果你装了eclipse的maven插件的话。右键点项目,Run
As下边Maven build 然后输入mybatis-generator:generate。
刷新一下项目:
搞定!