上面的兩篇文章,分別是MyBatis的入門小程序和MyBatis的配置XML解析,有需要的可以先去看看這兩篇文章,本篇文章,會來講解SQL映射XML文件的寫法以及如何使用。
MyBatis真正的力量在於其映射語句。這裏應該是奇蹟發生的地方。SQL映射的XML文件是相當簡單的。如果與功能對等的JDBC相比較,你會發現它減少了大約95%的代碼量。MyBatis的構建應該聚焦於SQL的XML文件的構建,使得其遠離普通的方式。
SQL的映射文件有很少幾個頂級元素(按照他們應該被定義的順序)
--cache:配置給定命名空間的緩存;
--cache-ref:從其他命名空間引入緩存配置;
--resultMap:最複雜,也是最優作用的元素,用來描述如何從數據庫結果集中加載你的對象,這個比較複雜,需要花點時間理解,理解了使用起來很是方便;
--sql:可以重用的SQL塊,也可以被其他語句引用;
--insert:映射插入語句;
--update:映射更新語句;
--delete:映射刪除語句;
--select:映射查詢語句
下面將以語句本身開始描述每個元素的細節。
select
查詢語句在使用MyBatis時候最常用的元素之一,查詢算是在數據庫中最常見的操作。
<select id="findById" parameterType="int" resultType="com.wpl.mybatisdemo.User">
select
*from user where id=#{id}
</select>
這個語句被稱爲findById(id="findById"),後面使用的時候,通過namespace加上id來確定該條語句,因此每一個id都是唯一的,使用了int類型的參數(parameterType="int"),並返回一個User的類型的對象(resultType="com.wpl.mybatisdemo.User")其中上面是參數類的全完限定名根據上面文章應該可以使用別名,這樣以後再使用到User時候方便很多。select元素有很多屬性允許我們自己去裝配,來決定每個語句的作用細節
上面需要注意的就是resultType和resultMap不能夠同時使用,具體resultMap是如何使用的後面會詳細的介紹。
insert,update,delete這三個在實現的時候非常的相似,這三個都沒有resultType或是resultMap返回結果的設置,都只有輸入參數的設置。
<insert
id="insertAuthor"
parameterType="domain.blog.Author"
flushCache="true"
statementType="PREPARED"
keyProperty=""
useGeneratedKeys=""
timeout="20000">
<update
id="insertAuthor"
parameterType="domain.blog.Author"
flushCache="true"
statementType="PREPARED"
timeout="20000">
<delete
id="insertAuthor"
parameterType="domain.blog.Author"
flushCache="true"
statementType="PREPARED"
timeout="20000">
下面是insert,update和delete的使用語句示例
<insert id="insertAuthor" parameterType="domain.blog.Author">
insert into Author (id,username,password,email,bio)
values (#{id},#{username},#{password},#{email},#{bio})
</insert>
<update id="updateAuthor" parameterType="domain.blog.Author">
update Author set
username = #{username},
password = #{password},
email = #{email},
bio = #{bio}
where id = #{id}
</update>
<delete id="deleteAuthor” parameterType="int">
delete from Author where id = #{id}
</delete>
sql
這個元素是可以被用來定義可以重用的SQL代碼段,這樣在重複使用某一個代碼段的時候可以考慮使用sql這個屬性
<sql id="userColumns">id,username,password</sql>
上述的代碼段就可以包含其他語句中,例如
<select id="findUserbyId" parameterType="int" resultType="com.wpl.mybatisdemo.User">
select <include refid="userColumns"/>
from user where id=#{id}
</select>
resultMap
這是一個很重要也是一個比較難理解的一個屬性吧,使用的很多,需要好好理解一下。
上面是數據庫中數據,有三個字段,理論上我們在構建Javabean的時候應該要和這些字段名一樣定義屬性。但是如果沒有這時候可以使用到resultMap這個屬性。
上面是Javabean。
<select id="findById2" parameterType="int" resultMap="userMap">
select
*from user where user_id=#{id}
</select>
<resultMap type="com.wpl.mybatisdemo.User" id="userMap">
<id property="id" column="user_id"/><!--數據庫的主鍵-->
<result property="name" column="user_name"/>
<result property="age" column="user_age"/>
</resultMap>
這樣就可以不用更改數據庫的列名或是Javabean屬性名,依然可以實現對數據庫的查詢。其中在<resultMap中 id的表示數據庫的主鍵,其他的使用result。