Oracle mybatis 新增返回主鍵ID
- 2019 年 11 月 7 日
- 筆記

寫上
<selectKey resultType="String" order="BEFORE" keyProperty="enterp_no"> SELECT PRSP_CRM_ENTERP_ID.nextval FROM DUAL </selectKey>
其中:PRSP_CRM_ENTERP_ID.nextval 是oracle 序列自增。因為oracle 中沒有自增設置。。
DUAL : 這個不需要變化。
resultType : 正常的返回值。 也就是 PRSP_CRM_ENTERP_ID.nextval 的返回值類型
order : 這個oracle 必須寫BEFORE ,mysql 是after 。
keyProperty: 這個是你的實體類中的一個屬性。
注意:

如何操作呢?

這裡上面明顯new 一個對象 但是只存了兩個值。如果執行了上面一個新增語句,那麼這個 ID 就會映射到實體類中了。。直接取得就好了。。
注意:不能直接取 retID 不然這個永遠都是 1。。。 不要采坑
mysql 中 如下:
- <insert id="insert" parameterType="cn.***.beans.LogObject" >
- <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">
- SELECT LAST_INSERT_ID() AS ID
- </selectKey>
- INSERT INTO S_T_LOGS (
- ID,
- USER_ID,
- USER_NAME,
- USER_IP,
- OPERATION_TIME,
- DESCRIPTION,
- RESOURCE_ID)
- VALUES (
- #{id},
- #{userId},
- #{userName},
- #{userIp},
- #{operationTime},
- #Xml程式碼 insert id="insert" parameterType="cn.***.beans.LogObject" > selectKey resultType="java.lang.Integer" order="BEFORE" keyProperty="id"> SELECT LOGS_SEQ.nextval AS ID FRO,
- #{resourceId})
- </insert>