mybatis插入數據並返回主鍵(oracle)

通常我們執行一個inser語句,即使有返回,也只是會返回影響了多少條數據

@insert("insert into t_user (id,name) values (suser.nextval,#{item.name,jdbcType=VARCHAR})")
void insert(@Param("item") TUser t);

但在有些時候,我們還需要獲得插入數據的主鍵,在oracle數據庫中,主鍵並沒有辦法自動增長,無法使用insert對應的useGeneratedKeys和keyProperty屬性自動返回增加的主鍵。

這時我們可以使用<selectKey>標籤。

@insert("insert into t_user (id,name) values (#{item.id,jdbcType=NUMERIC},#{item.name,jdbcType=VARCHAR})")
@SelectKey(statement="select suser.nextval from dual", keyProperty="item.id", before=true, resultType=Long.class)
void insert(@Param("item") TUser t);

在上面selectKey中

before=true,表示該語句會執行在insert之前。

statement="select suser.nextval from dual",表示我們在這裏獲取下一個序列值,將該值作爲主鍵。

resultType=Long.class,表示獲取的值爲long類型。

keyProperty="item.id",表示把生成的序列值放入參數TUser中的id屬性中。

此時,在我們的參數@Param("item") TUser t中,他的id值就已經是我們所獲取的最新的序列。然後程序會再執行@insert內容,將id值作爲參數傳遞進去。

 

原文:https://www.cnblogs.com/yxth/p/9755713.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章