使用generator自动生成Mybatis映射配置文件

在使用mybatis时,映射文件的配置非常麻烦,对于做逻辑不是很复杂,功能不是特别关键的模块的时候,我们没有必要手动书写,可以使用generator工具生成。
generator工具实际上就是根据数据库建好的数据结构,通过自定义的类名,生成对应的实体和映射文件。

下载相关的资源

资源下载地址:csdn资源下载

配置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>  
<!-- 数据库驱动-->  
    <classPathEntry  location="mysql-connector-java-5.1.25-bin.jar"/>  
    <context id="DB2Tables"  targetRuntime="MyBatis3">  
        <commentGenerator>  
            <property name="suppressDate" value="true"/>  
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->  
            <property name="suppressAllComments" value="true"/>  
        </commentGenerator>  
        <!--数据库链接URL,用户名、密码 -->  
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/springdemo" userId="root" password="">  
        </jdbcConnection>  
        <javaTypeResolver>  
            <property name="forceBigDecimals" value="false"/>  
        </javaTypeResolver>  
        <!-- 生成模型的包名和位置-->  
        <javaModelGenerator targetPackage="com.aheizi.domain" targetProject="src">  
            <property name="enableSubPackages" value="true"/>  
            <property name="trimStrings" value="true"/>  
        </javaModelGenerator>  
        <!-- 生成映射文件的包名和位置-->  
        <sqlMapGenerator targetPackage="com.aheizi.mapping" targetProject="src">  
            <property name="enableSubPackages" value="true"/>  
        </sqlMapGenerator>  
        <!-- 生成DAO的包名和位置-->  
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.aheizi.Dao" targetProject="src">  
            <property name="enableSubPackages" value="true"/>  
        </javaClientGenerator>  
        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->  
        <table tableName="user_t" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>  
</generatorConfiguration>  

生成属于自己的配置文件,需要根据自己的数据库改动connectionURL和tableName,根据自己的工程需要的目录改动targetPackage,设置自己的domainObjectName。

生成配置文件

在此目录打开CMD(shift+鼠标右键,如果安装了Git,直接git Bash here),执行命令

java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite

执行完后src目录下就已经自动生成dao,mapping,model文件内容了。

参考fengshizty的博客

posted @ 2015-09-06 16:44  aheizi  阅读(376)  评论(0编辑  收藏  举报