转载:http://blog.csdn.net/u013769320/article/details/42319631
最近在做一个项目,因为已经把数据库建好了,再一一写model,mapper的话,就显得重复了,于是上网百度,发现可以使用Mybatis Genetator反向生成model,mapper。经实验,确实不错,记录下来,以备后用。
需要的工具:
src文件夹存放生成的model,mapper代码;
config.xml配置文件:指定了一系列的属性,如需要使用的数据库表,数据库连接需要的信息,代码生成规范等;
mybatis-generator-core-1.3.2.jar是Mybatis Generator必需的jar包(generator生成器core核心包)
还需要的jar文件即数据库驱动,如这里的Mysql驱动和SQL Server驱动
配置文件:
- <span style="font-size:12px;"><?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>
- <!-- 数据库驱动,这里选择的是
- <span style="color:#ff6600;">
- Sql Server</span>的驱动
- -->
- <classPathEntry location="sqljdbc4.jar"/>
- <context id="DB2Tables" targetRuntime="MyBatis3">
- <commentGenerator>
- <property name="suppressDate" value="true"/>
- <!-- 是否去除自动生成的注释 true:是 : false:否 -->
- <property name="suppressAllComments" value="true"/>
- </commentGenerator>
- <!--数据库驱动,URL,用户名、密码 -->
- <jdbcConnection driverClass="com.microsoft.sqlserver.jdbc.SQLServerDriver" connectionURL="jdbc:sqlserver://192.168.1.101:1433; DatabaseName=Contract" userId="root" password="root">
- </jdbcConnection>
- <javaTypeResolver>
- <property name="forceBigDecimals" value="false"/>
- </javaTypeResolver>
- <!-- 生成model的包名和位置 ,包名应该和工程保存一致,不然等下导入代码时,会报错-->
- <javaModelGenerator targetPackage="com.<span style="font-family: Arial, Helvetica, sans-serif;">mine</span>.model" targetProject="src">
- <property name="enableSubPackages" value="true"/>
- <property name="trimStrings" value="true"/>
- </javaModelGenerator>
- <!-- 生成映射文件的包名和位置-->
- <sqlMapGenerator targetPackage="com.mine.mapper" targetProject="src">
- <property name="enableSubPackages" value="true"/>
- </sqlMapGenerator>
- <!-- 生成DAO的包名和位置-->
- <javaClientGenerator type="XMLMAPPER" targetPackage="com.mine.mapper" targetProject="src">
- <property name="enableSubPackages" value="true"/>
- </javaClientGenerator>
- <!-- 要生成哪些表-->
- <table schema="zjh" tableName="example" domainObjectName="Example" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
- <ignoreColumn column="name" />
- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
- </table>
- </context>
- </generatorConfiguration></span>
table标签详解
1. 属性
schema即为数据库名,tableName为对应的数据库表,domainObjectName是要生成的实体类。若要生成例子可将enableCountByExample等设为true, 就会生成一个对应domainObjectName的Example类,false则不生成,默认策略是true。
类似的还有enableUpdateByExample、enableDeleteByExample、enableSelectByExample、selectByExampleQueryId属性2. 子标签
若要对某些数据库字段进行操作,可以在table标签中加入如下标签
1)忽略某个字段
<ignoreColumn column="name" />
2)无论数据库字段是何类型,生成的类属性都是varchar
<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
生成代码:
打开windows下的Dos窗口或者Linux下的Terminal窗口,使用cd指令进入到图示目录,然后输入指令:java -jar ./mybatis-generator-core-1.3.2.jar -configfile ./config.xml -overwrite
Ok,到此结束。