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>
Mybatis操作后返回关键字段技巧
本文介绍了在使用Mybatis进行数据插入和更新时,如何获取并返回关键字段的值。对于插入操作,当ID由数据库自动生成时,通过在Service层生成UUID并在XML中配置返回ID的方式实现。而在更新场景中,例如新增子表数据后更新主表字段,可以通过先查询子表数据量,然后更新主表并返回最新字段值,或者直接更新并返回新值的方法来达成目标。
4617

被折叠的 条评论
为什么被折叠?



