【Mybatis】【1】insert/update 数据后返回关键字段

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>