MyBatis自动创建代码
在使用MyBatis作为数据持久层时,一大堆javabean与表的映射,十分繁琐。然而,有MyBatis-generator这个自动划创建代码,会使我们事半功倍。它的操作非常简单,供以下三步:
- 下载jar
- 创建配置文件
- JAVA命令执行
下载jar
- mybatis-3.3.0.jar
- mybatis-generator-core-1.3.2.jar
- mysql-connector-java-5.1.38.jar
- 创建src文件夹、config.xml文件
如图:
小伙伴们可以去Maven中央库下载对应jar,当然也可以使用以下链接下载: - http://download.csdn.net/detail/xiadi934/9426506
修改配置文件
修改config.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.38.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否生成注释代时间戳-->
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/test" userId="root" password="123456">
</jdbcConnection>
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成实体类地址 -->
<javaModelGenerator targetPackage="test.domain" targetProject="src">
<!-- 是否在当前路径下新加一层schema, true:com.oop.eksp.user.model.[schemaName] -->
<property name="enableSubPackages" value="true"/>
<!-- 是否针对string类型的字段在set的时候进行trim调用 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成mapxml文件 -->
<sqlMapGenerator targetPackage="test.mapping" targetProject="src">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成mapxml对应client,也就是接口dao -->
<javaClientGenerator type="XMLMAPPER" targetPackage="test.IDao" targetProject="src">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 配置表信息 -->
<table tableName="base_enterprise" domainObjectName="Enterprise" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
<!-- tableName为对应的数据库表 domainObjectName是要生成的实体类 enable*ByExample
是否生成 example类 -->
<!-- 忽略列,不生成bean 字段 -->
<ignoreColumn column="FRED" />
<!-- 指定列的java数据类型 -->
<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
</table>
<table tableName="base_manager" domainObjectName="Manager" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
以上注释在运行时请删除
JAVA命令执行
打开CMD命令,CD至该目录下,执行以下命令(也可以写成bat文件)
java -jar mybatis-generator-core-1.3.2.jar -configfile config.xml -overwrite
出现以下提示表示执行成功
MyBatis Generator finished successfully.
生成代码文件如下图: