実際には、@Options
アノテーションを使用してそれを行うことができます(データベースでauto_incrementまたは同様のものを使用している場合):
@Insert("insert into table3 (id, name) values(null, #{name})")
@Options(useGeneratedKeys=true, keyProperty="idName")
int insertTable3(SomeBean myBean);
keyProperty="idName"
SomeBean の key プロパティの名前が「id」の場合、この部分は不要であることに注意してください。keyColumn
MyBatis が自分で主キー列を見つけられないまれなケースのために、利用可能な属性もあります。@Options
を使用すると、メソッドをいくつかのデフォルト パラメータに送信することにも注意してください。ドキュメントを参照することが重要です (以下にリンクされています -- 現在のバージョンの 60 ページ)。
(古い回答) (ごく最近の)@SelectKey
注釈は、より複雑なキーの取得 (シーケンス、identity() 関数など) に使用できます。MyBatis 3 ユーザー ガイド(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 アノテーションを使用して ID 値を取得する方法を示します。
@Insert("insert into table2 (name) values(#{name})")
@SelectKey(statement="call identity()", keyProperty="nameId", before=false, resultType=int.class)
int insertTable2(Name name);