天天看點

MyBatis的xml檔案中主鍵操作

注: MySQL中可直接使用 uuid() 函數生成uuid

<!-- 新增 -->
    <insert id="insert" parameterType="com.xxx.xxx.MiniPollingImage" useGeneratedKeys="true" keyProperty="id">
        <selectKey keyColumn="id" keyProperty="id" resultType="string" order="BEFORE">
        	<!-- selectKey 标簽表示子查詢中主鍵的提取問題
             	 keyColumn:表示查詢語句傳回結果的列名
             	 keyProperty:表示對應的 domain 對象(指 parameterType 指定的對象)中需要被指派的屬性,一般是主鍵
             	 			  相當于java中設定實體類屬性一樣
             	 order="BEFORE:表示在插入語句之前執行
             	 resultType="int":表示傳回值得類型為int類型 -->
            -- SelectKey需要注意order屬性,像MySQL一類支援自動增長類型的資料庫中,order需要設定為AFTER才會取到正确的值,像Oracle這樣取序列的情況,需要設定為BEFORE

			-- 在上面示例的insert用法中,就是order屬性設定成了BEFORE才導緻自增屬性沒有生效。改成AFTER後,主鍵就開始自增了


			select replace(uuid(), '-', '') as id from dual
        </selectKey>
        
        INSERT INTO mini_polling_image(
            id,
            image_url,
            type,
            product_id,
            sort,
            created_time,
            created_by,
            last_update_by,
            last_update_time
        ) VALUES (
            #{id},
            #{imageUrl},
            #{type},
            #{productId},
            #{sort},
            #{createdTime},
            #{createdBy},
            #{lastUpdateBy},
            #{lastUpdateTime}
        )
    </insert>
           

   注意:

     在做關聯表插入操作時,需要根據主表的 主鍵 id 作詳情表的屬性值,最笨的方法就是,先插入主表,然後通過查詢傳回剛剛插入的主鍵id,繼續添加詳情表資料

   新方案:

     使用 keyProperty和useGeneratedKeys 屬性

     useGeneratedKeys參數隻針對 insert 語句生效,預設為 false。當設定為 true 時,表示如果插入的表以自增列為主鍵,則允許 JDBC 支援自動生成主鍵(在上例中即使用selectKey生成的主鍵),并可将自動生成的主鍵傳回。

   具體用法:

    

useGeneratedKeys="true" keyProperty="對應的主鍵的對象"

   上面的SQL語句後如下:

insert!selectKey - ==>  Preparing: select replace(uuid(), '-', '') as id from dual 
insert!selectKey - ==>  Parameters: 
insert!selectKey - <==  otal: 1


JDPollingImageDao.insert - ==>  Preparing: INSERT INTO mini_polling_image( id, image_url, type, product_id, sort, created_time, created_by, last_update_by, last_update_time ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ? ) 
JDPollingImageDao.insert - ==>  Parameters: b857ca5a85df11e98058c70bde3c8e14(String), https://img14.360buyimg.com/n1/jfs/t1/40230/29/6518/60461/5cd12bc8E19b67178/cd0de44a4c68b35c.jpg(String), 1(String), 12797839349(String), 1(Integer), 2019-06-03 17:12:44.689(Timestamp), admin(String), null, null
JDPollingImageDao.insert - <==  Updates: 1