Mybatis筆記
1.ibatis是mybatis的前身。
2.mybatis比hibernate靈活,性能也比hibernate好,而且也比較輕量級。
3.什么是mybatis:
MyBatis是支持普通SQL查詢,存儲過程和高級映射的優秀持久層框架。
MyBatis消除了幾乎所有的JDBC代碼和參數的手工設置以及結果集的檢索。
MyBatis使用簡單的XML或注解用于配置和原始映射,
將接口和Java的POJOs(Plan Old Java Objects,普通的Java對象) 映射成 數據庫中的記錄.
4.orm工具的基本思想:
無論是用過的hibernate,mybatis,你都可以發現他們有一個共同點:
1. 從配置文件(通常是XML配置文件中)得到 sessionfactory.
2. 由sessionfactory 產生 session
3. 在session 中完成對數據的增刪改查和事務提交等.
4. 在用完之后關閉session 。
5. 在java 對象和 數據庫之間有做mapping 的配置文件,也通常是xml 文件。
5.對于物理分頁方案,不同的數據庫,有不同的實現方法。
對于 mysql 來說 就是利用 limit offset, pagesize 方式來實現的。
oracle 是通過 rownum 來實現的。
6.實現 mybatis 物理分頁,一個最簡單的方式是,是在你的mapper的SQL語句中直接寫類似如下方式 :
<select id="getUserArticles" parameterType="Your_params" resultMap="resultUserArticleList">
select user.id,user.userName,user.userAddress,article.id aid,article.title,article.content from user,article
where user.id=article.userid and user.id=#{id} limit #{offset},#{pagesize}
</select>
用這種方式,肯定可以實現分頁。這是簡單的一種方式。
但更通用的一種方式是用 mybatis 插件的方式, 代碼參考Z_LiamMS_V0.5中的PagePlugin.java
7.總體說來mybatis 動態SQL 語句主要有以下幾類:
1). if 語句 (簡單的條件判斷)
<select id="dynamicIfTest" parameterType="Blog" resultType="Blog">
select * from t_blog where 1 = 1
<if test="title != null">
and title = #{title}
</if>
<if test="content != null">
and content = #{content}
</if>
<if test="owner != null">
and owner = #{owner}
</if>
</select>
2). choose (when,otherwize) ,相當于java 語言中的 switch ,與 jstl 中的choose 很類似.
<select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">
select * from t_blog where 1 = 1
<choose>
<when test="title != null">
and title = #{title}
</when>
<when test="content != null">
and content = #{content}
</when>
<otherwise>
and owner = "owner1"
</otherwise>
</choose>
</select>
3). trim (對包含的內容加上 prefix,或者 suffix 等,前綴,后綴)
<select id="dynamicTrimTest" parameterType="Blog" resultType="Blog">
select * from t_blog
<trim prefix="where" prefixOverrides="and |or">
<if test="title != null">
title = #{title}
</if>
<if test="content != null">
and content = #{content}
</if>
<if test="owner != null">
or owner = #{owner}
</if>
</trim>
</select>
4). where (主要是用來簡化sql語句中where條件判斷的,能智能的處理 and or ,不必擔心多余導致語法錯誤)
<select id="dynamicWhereTest" parameterType="Blog" resultType="Blog">
select * from t_blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="content != null">
and content = #{content}
</if>
<if test="owner != null">
and owner = #{owner}
</if>
</where>
</select>
5). set (主要用于更新時)
<update id="dynamicSetTest" parameterType="Blog">
update t_blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="content != null">
content = #{content},
</if>
<if test="owner != null">
owner = #{owner}
</if>
</set>
where id = #{id}
</update>
6). foreach (在實現 mybatis in 語句查詢時特別有用)
(6.1)單參數List的類型
<select id="dynamicForeachTest" resultType="Blog">
select * from t_blog where id in
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
對應的Mapper:
public List<Blog> dynamicForeachTest(List<Integer> ids);
(6.2)數組類型的參數
<select id="dynamicForeach2Test" resultType="Blog">
select * from t_blog where id in
<foreach collection="array" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
對應mapper:
public List<Blog> dynamicForeach2Test(int[] ids);
(6.3)Map 類型的參數
<select id="dynamicForeach3Test" resultType="Blog">
select * from t_blog where title like "%"#{title}"%" and id in
<foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
mapper 應該是這樣的接口:
public List<Blog> dynamicForeach3Test(Map<String, Object> params);
8.使用mybatis代碼生成工具
1)下載mybatis-generator-core-1.3.2.jar,拷貝到WEB-INF/lib下
2)在數據庫中創建mybatis數據庫和category測試表
Drop TABLE IF EXISTS `category`;
Create TABLE `category` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`catname` varchar(50) NOT NULL,
`catdescription` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3)在用mybatis 代碼生成工具之前,相應的目錄必須先創建好:
com.liam.inter 用來存放mybatis 接口對象.
com.liam.mapper用來存放sql mapper對應的映射,sql語句等.
com.liam.model 用來存放與數據庫對應的model 。
4)配置文件 mbgConfiguration.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>
<!-- 配置mysql 驅動jar包路徑.用了絕對路徑 -->
<classPathEntry
location="D:\Work\Java\eclipse\workspace\myBatisGenerator\WebContent\WEB-INF\lib\mysql-connector-java-5.1.22-bin.jar" />
<context id="liam_mysql_tables" targetRuntime="MyBatis3">
<!-- 為了防止生成的代碼中有很多注釋,比較難看,加入下面的配置控制 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
<property name="suppressDate" value="true" />
</commentGenerator>
<!-- 注釋控制完畢 -->
<!-- 數據庫連接 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf8"
userId="root"
password="password">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 數據表對應的model 層 -->
<javaModelGenerator targetPackage="com.liam.model" targetProject="src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- sql mapper 隱射配置文件 -->
<sqlMapGenerator targetPackage="com.liam.mapper" targetProject="src">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 在ibatis2 中是dao層,但在mybatis3中,其實就是mapper接口 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.liam.inter" targetProject="src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 要對那些數據表進行生成操作,必須要有一個. -->
<table schema="mybatis" tableName="category" domainObjectName="Category"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
5)創建一個com.liam.test的package ,并在此package下建立一個測試的類GenMain:
public class GenMain {
public static void main(String[] args) {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
String genCfg = "/mbgConfiguration.xml";
File configFile = new File(GenMain.class.getResource(genCfg).getFile());
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = null;
try {
config = cp.parseConfiguration(configFile);
} catch (IOException e) {
e.printStackTrace();
} catch (XMLParserException e) {
e.printStackTrace();
}
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = null;
try {
myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
try {
myBatisGenerator.generate(null);
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
6)運行測試類的main方法,隨即生成mybatis相關代碼
7)如果你想生成example之類的東西,需要在<table></table>里面去掉:
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false"
這部分配置,這是生成Example而用的,一般來說對項目沒有用.
8)另外生成的sql mapper等,只是對單表的增刪改查,
如果你有多表join操作,你就可以手動配置。
如果調用存儲過程,你也需要手工配置。
這時工作量已經少很多了。