1. 程式人生 > >MyBatis學習(四)XML配置文件之SQL映射的XML文件

MyBatis學習(四)XML配置文件之SQL映射的XML文件

元素 數據庫 resultmap ash 有一點 oracl 解決 轉換成 插入語

SQL映射文件常用的元素:

  技術分享

1.select

  查詢語句是MyBatis最常用的語句之一。

  執行簡單查詢的select元素是非常簡單的:

<select id=”selectUser” parameterType=”int” resultType=”hashmap”>
    SELECT * FROM PERSON WHERE ID = #{id}
</select>

  這個語句被稱作selectUser,接受一個int類型的參數,返回的一個HashMap類型的對象。

  #{id}告訴MyBatis創建一個預處理參數,相當於JDBC中的"?"。

  接下裏介紹select元素的屬性:

  技術分享

  技術分享 

3.insert、update、delete

 介紹這三種元素的屬性:

技術分享

示例:

<insert id="insertUser" parameterType="com.dj.domain.User">
insert into User (id,username,password,email,bio)
values (#{id},#{username},#{password},#{email})
</insert>
<update id="updateUser" parameterType="com.dj.domain.User">
update User set
username = #{username},
password = #{password},
email = #{email},
bio = #{bio}
where id = #{id}
</update>
<delete id="deleteUser” parameterType="int">
delete from User where id = #{id}
</delete>

  

  如前所述,插入語句有一點多,它有一些屬性和子元素用來處理主鍵的生成。首先,如果你的數據庫支持自動生成主鍵的字段(比如 MySQL 和 SQL Server 數據庫),那麽你可以設置 useGeneratedKeys=”true”,而且設置 keyProperty 到你已經做好的目標屬性上。例如,如果上面的 Author 表已經對 id 使用了自動生成的列類型,那麽語句可以修改為:

<insert id="insertUser" parameterType="com.dj.domain.User" 
       useGenerateKeys="true" keyProperty="id">
insert into User (id,username,password,email,bio)
values (#{id},#{username},#{password},#{email})
</insert>

  MyBatis對於不支持自動生成類型的數據庫(如Oracle)或可能不支持自動生成主鍵的jdbc驅動來說,有另外一種方法來生成主鍵。

    <insert id="insertUser" parameterType="com.dj.domain.User">
        <selectKey keyProperty="id" resultType="int" order="BEFORE">
            select SEQUENCE_T_USER.nextval as id from dual
        </selectKey>
    insert into User (id,username,password,email,bio)
    values (#{id},#{username},#{password},#{email})
    </insert>

  select元素先運行,User的id會被設置,然後插入語句被調用。

  selectKey 元素描述如下:
  技術分享

  parameterType可以設置成基本數據類型和復雜類型,例如一個User類型。

4.resultMap

  resultMap是MyBatis最重要最強大的元素。它的作用就是告訴MyBatis將從結果集中取出的數據轉換成開發者所需要的對象。

  第一種情況,當你遇到查詢到的數據的列和需要返回的對象的屬性不一致時,可以使用resultMap進行處理。

  第二種情況,進行多表查詢時,返回的對象關聯到另一個對象,這時候簡單的映射已經不能解決問題了,必須使用resultMap元素來完成關聯映射。

 接下來我們對resultMap進行一個簡單的測試:待續。。。盡快更新。。

MyBatis學習(四)XML配置文件之SQL映射的XML文件