其實,這是有可能做到這一點,與@Options
註解(前提是你使用AUTO_INCREMENT或數據庫中的類似的東西):
@Insert("insert into table3 (id, name) values(null, #{name})")
@Options(useGeneratedKeys=true, keyProperty="idName")
int insertTable3(SomeBean myBean);
注意,如果在SomeBean關鍵屬性名爲「ID」的部分是沒有必要的。還有一個keyColumn
屬性可用,對於MyBatis無法自己找到主鍵列的罕見情況。還請注意,通過使用@Options
,您正在將您的方法提交給一些默認參數;查閱文檔非常重要(鏈接如下 - 當前版本的第60頁)!
(舊的回答)(相當近)@SelectKey
註釋可用於更復雜的密鑰檢索(序列,identity()函數...)。下面介紹一下MyBatis 3 User Guide(PDF)提供的例子:
這個例子顯示使用@SelectKey註釋檢索序列值的 插入前:
@Insert("insert into table3 (id, name) values(#{nameId}, #{name})")
@SelectKey(statement="call next value for TestSequence", keyProperty="nameId", before=true, resultType=int.class)
int insertTable3(Name name);
這個例子顯示使用@SelectKey註釋在插入後檢索標識值:
@Insert("insert into table2 (name) values(#{name})")
@SelectKey(statement="call identity()", keyProperty="nameId", before=false, resultType=int.class)
int insertTable2(Name name);
假設您使用註釋選擇並使用@Options(useGeneratedKeys = true) – Lucky 2016-03-03 09:16:53