oracle及mysql+mybatis新增一條記錄並獲取該記錄的id
阿新 • • 發佈:2019-02-15
在特定的業務需求中,我們有時需要獲取剛新增記錄的id,在mybatis框架下可以通過idProperty配置獲取到,而對於mySQL和oracle資料庫,獲取方法有一點區別,mySql可以通過last_insert_id獲取,oracle則通過seq.nextval獲取,獲取方式如下:
一:mysql獲取新增記錄id的例子
Mybatis對映檔案中SQL語句:
<insert id="insert" parameterType="com.xxx.xxxx.User">
insert into t_user (name)
values (#{name})
<selectKey resultType="Long" order="AFTER" keyProperty="id">
SELECT LAST_INSERT_ID() AS id
</selectKey>
</insert>
可通過System.out.println(user.getId)檢查是否獲取到
二:oracle對映檔案中SQL語句:
<insert id="insert" parameterType="com.xxx.xxxx.User" > //獲取序列值,並賦值到物件的id欄位 <selectKey keyProperty="id" resultType="DECIMAL" order="BEFORE"> select seq_t_user.nextval from dual </selectKey> insert into t_user(ID, NAME)也可通過System.out.println(user.getId)檢查是否獲取到,從SQL可以看出mysql是在插入之後獲取id,而oracle是在插入資料之前從序列直接獲取,
//獲取上面物件中id欄位的值values (#{id,jdbcType=DECIMAL}, #{name,jdbcType=VARCHAR}) </insert>
因此對於order引數,mysql對應的是AFTER,而oracle對應的是BEFORE