【Mybatis】insert/update 数据后返回关键字段
1,插入 insert
场景:ID字段的值是数据库表“默认/表达式”(sys_guid())自动生成,插入一条数据到数据库后,需要获取该条数据的ID
解决方案:
(1) uuid :
UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
java UUID 默认小写 , Oracle sys_guid() 函数 默认大写 ,所以这里 转大写
(2)xml中插入数据立即返回ID
int insertExchangeInfoList(ExchangeInfoList infoDetail);
//Dao层传过去的数据必须是实体类,不能是单个字段
--BEFORE表示在数据插入前获取,AFTER表示在数据插入后获取
<insert id="insertExchangeInfoList"> <selectKey resultType="String" keyProperty="id" order="AFTER"> select exchange_list_no from exchange_info_list </selectKey> insert into exchange_info_list (exchange_list_no, exchange_no , gift_no, exchange_num, used_score, remark, create_time, create_tlr) value ( sys_guid(), #{exchangeNo}, #{giftNo}, #{exchangeNum}, #{usedScore},#{remark}, sysdate, #{createTlr} ) </insert>
2,更新 update
场景:子表新增一条数据,主表某字段要+1,要获取该字段的值(例:新增一条文章评论,文章表的评论数字段要+1,并返回最新的评论数)
解决方案:
(1)子表数据新增后,查询有效数据条数。更新主表。
(2)更新主表时直接+1,并返回数据
int updateCommentCount(Article info); //Dao层传过去的数据必须是实体类,不能是单个字段
<update id="updateCommentCount"> <selectKey resultType="SHORT" keyProperty="commentCount" order="AFTER"> select (select A.COMMENT_COUNT FROM ARTICLE A WHERE A.ID = #{id}) commentCount from DUAL </selectKey> update ARTICLE A set A.COMMENT_COUNT = A.COMMENT_COUNT + 1 where A.ID = #{id} </update>