1、基本概念
MyBatis 本是apache的一個開源項(xiàng)目iBatis, 2010年這個項(xiàng)目由apache software foundation 遷移到了google code,并且改名為MyBatis 。MyBatis是一個基于Java的持久層框架。iBATIS提供的持久層框架包括SQL Maps和Data Access Objects(DAO)MyBatis 消除了幾乎所有的JDBC代碼和參數(shù)的手工設(shè)置以及結(jié)果集的檢索。MyBatis 使用簡單的 XML或注解用于配置和原始映射,將接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java對象)映射成數(shù)據(jù)庫中的記錄。
由于MyBatis屬于一種半自動的ORM框架,所以主要的工作就是配置Mapping映射文件,但是由于手寫映射文件很容易出錯,所以可利用MyBatis生成器自動生成實(shí)體類、DAO接口和Mapping映射文件。這樣可以省去很多的功夫,將生成的代碼copy到項(xiàng)目工程中即可。
使用自動生成有很多方式,可以在eclipse中安裝插件,但是以下將要介紹的這種方式我認(rèn)為很輕松,最簡單,不需要裝插件,只需要下幾個jar包即可,把它們放在一個目錄下面。
生成代碼需要的文件和jar包:

(上圖文件下載地址:使用文件)
其中有mybatis框架的jar包,數(shù)據(jù)庫驅(qū)動程序jar包以及MyBatis生成器jar包。其中的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>
<!-- 數(shù)據(jù)庫驅(qū)動 -->
<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>
<!--數(shù)據(jù)庫鏈接URL,用戶名、密碼 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://192.168.50.116/mysql" userId="root" password="admin116">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置 -->
<javaModelGenerator targetPackage="test.domain" 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>
<!-- 生成DAO的包名和位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="test.IDao" targetProject="src">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是數(shù)據(jù)庫中的表名或視圖名 domainObjectName是實(shí)體類名 -->
<table tableName="user_table" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
對應(yīng)以上配置修改為自己的數(shù)據(jù)庫信息,完成之后,只需要打開控制臺,進(jìn)入lib目錄下,執(zhí)行腳本:
Java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite
即可。


我的博客即將搬運(yùn)同步至騰訊云+社區(qū),邀請大家一同入駐:https://cloud.tencent.com/developer/support-plan?invite_code=sdfzx6n71s8z