1,插入 insert
場景:ID字段的值是數據庫表“默認/表達式”(sys_guid())自動生成,插入一條數據到數據庫后,需要獲取該條數據的ID
解決方案:
(1)Service層生成UUID
public static String getGUID() { UUID uuid = UUID.randomUUID(); return uuid.toString().replaceAll("-", "").toUpperCase(); }
String id = getGUID(); Article info = new Article (); info.setId(id); ...
(2)xml中插入數據立即返回ID
int insertArticle(Article info); //Dao層傳過去的數據必須是實體類,不能是單個字段
--BEFORE表示在數據插入前獲取,AFTER表示在數據插入后獲取 <insert id="insertArticle" > <selectKey resultType="String" keyProperty="id" order="BEFORE"> select sys_guid() as id from dual </selectKey> insert into ARTICLE <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> ID, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="id != null"> #{id,jdbcType=VARCHAR}, </if> </trim> </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>