Mybatis中使用mybatis-generator结合Ant脚本快速自动生成Model、Mapper等文件

使用过Mybatis的同学都知道,针对每一个项目中使用到的数据库表都需要建立其对应的数据库增删改查xxxMapper.xml文件、实体类xxx.java文件以及其他类用来调用进行数据库操作的xxxMapper.java文件。在开始学习Mybatis时,我相信不少人都是通过手动来建立这些文件的。毫无疑问,如果项目比较大的话还通过手动建立这些文件效率是非常低的,这时我们可以通过mybatis-generator来自动生成这些文件。但是,这个工具默认是以命令行的形式来生成相关文件的,因此我们可以通过写一个Ant脚本,每次需要建立这些文件时在eclipse中执行一下这个Ant脚本就可以自动生成了。完整步骤如下:

一 导入相关jar包

要想使用“mybatis-generator”需要在web项目的lib中导入对应的一个mybatis-generator-1.3.x.jar文件,Github上的下载地址:mybatis-generator的jar包下载

二 配置mybatis-generator的配置文件

(1)首先在项目中新建几个包用于存放对应的文件:

Mybatis中使用mybatis-generator结合Ant脚本快速自动生成Model、Mapper等文件

由上图可以看出,src/main/java用于存放Java源代码;src/main/env/dev用于存放开发环境下的配置文件(如:jdbc,缓存,日志等);src/main/resources用于存放通用的一些配置文件,在这里我们自动生成的Mapper.xml文件就存放在这个路径下;src/test/java表示测试代码,这里不管

注:如何在eclipse中添加这些源文件夹?

Mybatis中使用mybatis-generator结合Ant脚本快速自动生成Model、Mapper等文件

(2)在项目根目录下新建generatorConfig.xml和build_mybatis.xml:

这两个文件分别是“mybatis-generator”的配置文件和自动化的Ant脚本,在项目中的路径如下:

Mybatis中使用mybatis-generator结合Ant脚本快速自动生成Model、Mapper等文件

i)generatorConfig.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?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>
    <!--数据库驱动 -->
    <classPathEntry
        location="WebContent/WEB-INF/lib/mysql-connector-java-5.1.26-bin.jar" />
 
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressAllComments" value="true" /><!-- 是否取消注释 -->
            <property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳 -->
        </commentGenerator>
        <!-- 数据库连接信息 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://127.0.0.1:3306/ehcache_db" userId="root"
            password="root">
        </jdbcConnection>
 
        <!-- 只有一个属于forceBigDecimals,默认false。 如果字段精确超过0,生成BigDecimal 如果字段精确是0,总长度10-18生成Long;如果字段精确是0, 
            总长5-9生成Integer; 如果字段精确是0,总长小于5生成Short; 如果forceBigDecimals为true,统一生成BigDecimal -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
 
        <!--生成Model.java文件 -->
        <javaModelGenerator targetPackage="cn.zifangsky.model"
            targetProject="src/main/java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 是否针对string类型的字段在set的时候进行trim调用 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
 
        <!-- 生成Mapper.xml文件 -->
        <sqlMapGenerator targetPackage="sqlmaps"
            targetProject="src/main/resources">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
 
        <!-- 生成Mapper.java文件,即dao层 -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="cn.zifangsky.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
         
        <!-- 待生成的数据库中的表名,生成一个表对应的Java和xml文件就需要配置一段 -->
        <table tableName="user" domainObjectName="User"
            enableCountByExample="false" enableUpdateByExample="false"
            enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false">
        </table>
    </context>
</generatorConfiguration>

注:需要修改的一些地方可以参照我上面的注释进行修改,同时别忘了数据驱动的jar包

ii)build_mybatis.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<project default="genfiles" basedir=".">
    <property name="generated.source.dir" value="${basedir}" />
     
       <path id="ant.run.lib.path">
             <pathelement location="${basedir}/WebContent/WEB-INF/lib/mybatis-generator-core-1.3.2.jar"/>
       </path>
     
    <target name="genfiles" description="Generate the files">
        <taskdef name="mbgenerator" classname="org.mybatis.generator.ant.GeneratorAntTask"  classpathref="ant.run.lib.path"/>
        <mbgenerator overwrite="true" configfile="generatorConfig.xml" verbose="false">
            <propertyset>
                <propertyref name="generated.source.dir" />
            </propertyset>
        </mbgenerator>
    </target>
</project>

上面的代码就两个地方需要注意:一是“mybatis-generator”的jar包,二是需要对应的“generatorConfig.xml”文件

注:如果对Ant脚本不太熟悉的话,可以参考下我写的这篇文章:http://www.zifangsky.cn/444.html

三 测试

Mybatis中使用mybatis-generator结合Ant脚本快速自动生成Model、Mapper等文件

进行效果测试时,只需要把“build_mybatis.xml”这个文件拖到Ant视图中,然后点击执行这个脚本就可以自动生成我们需要的文件了,最后就是刷新一下项目结构就可以看到文件了,效果如下:

Mybatis中使用mybatis-generator结合Ant脚本快速自动生成Model、Mapper等文件

注:我测试使用到的数据库数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
SET FOREIGN_KEY_CHECKS=0;
 
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `namevarchar(32) DEFAULT NULL,
  `passwordvarchar(64) DEFAULT NULL,
  `email` varchar(64) DEFAULT NULL,
  `birthday` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
 
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `userVALUES ('1''admin''123456''[email protected]''2000-01-02');
INSERT INTO `userVALUES ('2''test''1234''[email protected]''1990-12-12');
INSERT INTO `userVALUES ('3''xxxx''xx''[email protected]''1723-06-21');



本文转自 pangfc 51CTO博客,原文链接:http://blog.51cto.com/983836259/1773597,如需转载请自行联系原作者