使用Mybatis-Generator自动生成Dao、Model、Mapping相关文件

最近一直在学习SSM框架,今天遇到一个关于MyBatis生成的问题,记录一下。

http://blog.csdn.net/zhshulin/article/details/37956105 我是根据这个博客进行测试的

首先介绍一下Mybatis属于半自动ORM,在使用这个框架中,工作量最大的就是书写Mapping的映射文件,由于手动书写很容易出错,我们可以利用Mybatis-Generator来帮我们自动生成文件。

1.相关文件:

2.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/myspring" userId="root" password="root">
         </jdbcConnection>
         <javaTypeResolver>
             <property name="forceBigDecimals" value="false"/>
         </javaTypeResolver>
   
         <javaModelGenerator targetPackage="test.model" targetProject="src">
             <property name="enableSubPackages" value="true"/>
             <property name="trimStrings" value="true"/>
         </javaModelGenerator>
       
         <sqlMapGenerator targetPackage="test.mapping" targetProject="src">
             <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
     
         <javaClientGenerator type="XMLMAPPER" targetPackage="test.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>

其中是参考了http://blog.csdn.net/zhshulin/article/details/23912615这篇博客

3.进行测试

在该目录按住Shift键,右键鼠标选择"在此处打开命令窗口",复制粘贴生成语句的文件代码即可。这一条在博客中没有提到,可是苦了我,不过幸好找到另一篇博客,算是解了谜团。http://www.cnblogs.com/smileberry/p/4145872.html

在命令行中输入语句

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

4.如果遇到这样错误的解决办法  

当用MyBatis生成的时候遇到问题了,出现前言中不允许有内容的问题,如果出现这样的问题,需要用Notepad++工具打开,选择格式以UTF-8无BOM格式编码,之后再运行就解决了,原理是将xml文件换成UTF-8格式的会有个BOM头  JAVA读取的时候就会报错

原文地址:https://www.cnblogs.com/shibazizhan/p/4540603.html