簡體   English   中英

當id / uuid存儲為二進制時,如何在使用MyBatis插入后返回鍵?

[英]How to return key after insert using MyBatis when the id/uuid as is stored as binary?

我們目前在我們的數據庫中有觸發器,為我插入的每條記錄分發uuid。 當我使用mybatis插入記錄時,我希望將uuid取回而不是已插入的行數。

從上一篇文章我讀到我可以做到

useGeneratedKeys="true" keyProperty="id"

但是我們將我們的uuid存儲為二進制文件,所以我想從插入中獲取非二進制uuid。 當我們插入東西時,我們使用'uuid2bin'和'bin2uuid'之類的函數,所以我希望使用這樣的函數從數據庫(MySQL)中檢索新生成的uuid。

關於如何讓新生成的uuid回來的任何建議?

我能想到的1兩個選項)使用MyBatis的Java中的轉換做TypeHandler或2)與返回格式化的UUID存儲過程包裝你的插件。

#1的問題在於您正在將負載從數據庫移動到您的應用程序,如果MySql是遠程的,可能會對性能產生影響。

使用#2,您需要在MyBatis中使用<select> 但是,您需要確保它實際提交。 此外,如果您正在使用MyBatis緩存,還需要在<select>設置flushCache=true

我會在<insert>標記內使用<selectKey> <insert>標記

<insert>
   <selectKey keyProperty="pk" resultType="Type" order="AFTER">
     select myDBFunction( (select triggerGeneratedColumnInBinary from myTable where pk = triggerLogicToRetrieveLastGenerated(...) ) );
   </selectKey>
   ...procedure call or insert...
</insert>

如果您要發送對象而不是Hashmap,則此代碼將在插入后使用觸發器生成列設置解釋器函數的結果。 該方法仍將返回行數,但您的對象將具有其鍵。

System.out.println(myObject.getPk()); //0
int rows = myMapper.insertMyClass(myObject); // sets the pk
System.out.println(myObject.getPK()); //324

useGeneratedKeys不會幫助你,因為它告訴MyBatis使用JDBC getGeneratedKeys方法來檢索數據庫內部生成的密鑰(例如,像MySQL或SQL Server這樣的RDBMS中的自動增量字段)。

方法返回一個值是更新行的數量。傳入參數的id是insertd row.as的id,如下所示:

 <insert id="insertSelectiveReturnKey" parameterType="com.test.dal.model.CostDO" useGeneratedKeys="true" keyProperty="id">
        insert into cost
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                id,
            </if>
            <if test="name != null">
                name,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=BIGINT},
            </if>
            <if test="name != null">
                #{name,jdbcType=TIMESTAMP},
            </if>
        </trim>
    </insert>


 CostDO costDO = new CostDO();
 costDO.setName("test");
 int updateNum = productMapper.insertSelectiveReturnKey(costDO);
 // updateNum is the number of updated rows.

productMapper.insertSelectiveReturnKey(costDO);
int id = costDO.getId();
// id is the id of insertd row

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM