表:create table play(iid int(10) not null primary key auto_increment,typeId int(3));
Play.java:
public class Play{
private Integer iID;
private Integer typeID;
...setter and getter省略...
}
play-mapper.xml:
<mapper namespace="PlayDAO">
<resultMap id="BaseResultMap" type="Play">
<id column="iid" property="iID" jdbcType="INTEGER" />
<result column="typeId" property="typeID" jdbcType="INTEGER" />
</resultMap>
<insert id="insert" parameterType="Play">
insert into play(typeId) values (#{typeID,jdbcType=INTEGER})
<selectKey keyProperty="iID" resultType="int" order="AFTER">
select LAST_INSERT_ID()
</selectKey>
</insert>
</mapper>
說明:
1、 order="AFTER" 表示selectKey的動作在insert into...執行之后執行。
2、為了說明問題,本例特別讓java類中的屬性名與xml配置文件中的column名不同,需要特別注意 selectKey的keyProperty屬性必須是java類中的屬性名。
補充:
在Oracle中的用法:先為主鍵創建一個序列 create sequence Play_Sequence increment by 1 start with 1 nomaxvalue;
<insert id="insert" parameterType="Play"><selectKey keyProperty="iID" resultType="int" order="BEFORE" >
select Play_Sequence.nextval from dual
</selectKey>
insert into play( iid , typeId) values ( #{ iID ,jdbcType=INTEGER} , #{ typeID ,jdbcType=INTEGER})</insert>
說明:
1、無需為序列創建觸發器(trigger),order="BEFORE"確定了在插入數據之前取得主鍵,再將主鍵隨其他字段一起插入即可。
2、做了一個試驗,在創建觸發器的情況下,使selectKey的order="AFTER",再使selectKey選擇序列的currval,發現currval還未加1。所以只能用1中的方法。
