mybatis代码生成实例

来源:互联网 发布:快压 mac版本 编辑:程序博客网 时间:2024/06/06 00:51

      目前项目开发用到了mybatis,在自己手写了几个mapper文件和实体类之后,觉得是苦力活,同事推荐看一下mybatis的代码生成器,参照网上所写,没有可以实现的,还是要自己动手,主要问题还是相对路径的问题,自己用了绝对路径,可以实现代码生成。

        mybatis代码生成需要以下几个文件:

        mybatis-3.2.0-SNAPSHOT.jar(mybatis核心包)

        mybatis-generator-core-1.3.1.jar(mybatis代码生成核心包)

        sqljdbc4.jar(数据库连接包驱动包)

        另外一个,也就是主要的配置文件,generatorConfig.xml,文件名称可以自定义,目录位置是src下。

<?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 >  <!-- 设置mssql驱动路径 -->  <classPathEntry location="D:\Workspaces\Rtx\mybatisGeneratorDemo\WebRoot\WEB-INF\lib\sqljdbc4.jar" />    <context id="context1"  targetRuntime="MyBatis3"><!-- 设置不生成simple对象 -->   <plugin type="org.mybatis.generator.plugins.RenameExampleClassPlugin">     <property name="searchString" value="Example$" />     <property name="replaceString" value="NewName" />   </plugin>   <!-- 取消生成的代码注释 -->    <commentGenerator><property name="suppressAllComments" value="true"/></commentGenerator>  <!-- jdbc连接信息 -->      <jdbcConnection driverClass="com.microsoft.sqlserver.jdbc.SQLServerDriver"        connectionURL="jdbc:sqlserver://localhost:1433;databaseName=rtxtmsV1.0"       userId="sa" password="123" />      <!-- 生成domain对象 -->      <javaModelGenerator targetPackage="com.rtx.domain" targetProject="D:\Workspaces\Rtx\mybatisGeneratorDemo\src" />      <!-- 生成用于查询的mapper对象 -->      <sqlMapGenerator targetPackage="com.rtx.dao.mapper" targetProject="D:\Workspaces\Rtx\mybatisGeneratorDemo\src" />      <!-- 生成dao的类文件以及配置文件 -->      <javaClientGenerator targetPackage="com.rtx.dao" targetProject="D:\Workspaces\Rtx\mybatisGeneratorDemo\src" type="XMLMAPPER" />       <!-- 想要生成的数据库表,自动化工具会根据该表的结构生成相应的domain对象,下面几个属性设置成false,是在mapper文件里不生成这些方法 -->       <table schema="" tableName="RTX_BASIC_COMMODITY" domainObjectName="RtxBasicCommodity"       enableCountByExample="false" enableUpdateByExample="false"            enableDeleteByExample="false" enableSelectByExample="false"            selectByExampleQueryId="false"     >    </table>     <table schema="" tableName="RTX_BASIC_ENTRUST_RULE" domainObjectName="RtxBasicEntrustRule" >    </table>       </context>  </generatorConfiguration>
生成代码的步骤是:

1.进入mybatis-generator-core-1.3.1.jar(mybatis代码生成核心包)所在的目录

 D:\Workspaces\Rtx\mybatisGeneratorDemo\WebRoot\WEB-INF\lib

2.执行java命令,运行mybatis-generator-core-1.3.1.jar及generatorConfig.xml文件

java -jar mybatis-generator-core-1.3.1.jar -configfile D:\Workspaces\Rtx\mybatisGeneratorDemo\src\generatorConfig.xml -overwrite

生成代码截图


刷新项目就可以看见生成的domain实体和mapper文件还有到接口,当然包名都是要自己手动建的,该方法还不能自动建包,由于项目的命名原因,生成的文件和代码不能直接拿到项目中用,但是对于一个表都很多字段的时候,生成器的优势还是很明显的。

此版本还是比较的初级,以后会继续学习mybatis代码生成器,争取做的更好。

原创粉丝点击