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值作為參數傳遞進去。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM