mybatis插入数据后将其ID返回

  • 背景

mybatis没有关联保存的功能,所以主从表需要分开保存,这就涉及到主表保存后要再次获取主表ID的环节,以下介绍mybatis插入数据后返回其自增ID的两种方式

  • 方案

  1、sql获取

<insert id="insert" parameterType="com.erp.oa.entity.MessageCommentDO" >
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
      select LAST_INSERT_ID()
    </selectKey>
    insert into message_comment (ID, comment_man, comment_detail, 
      insert_time)
    values (#{id,jdbcType=INTEGER}, #{commentMan,jdbcType=INTEGER}, #{commentDetail,jdbcType=VARCHAR}, 
      #{insertTime,jdbcType=TIMESTAMP})
  </insert>
keyProperty="id"中的id对应实体中的主键

  2、mybatis标签属性获取

<insert id="insert" parameterType="com.erp.oa.entity.MessageCommentDO" useGeneratedKeys="true" keyProperty="id">
    insert into message_comment (ID, comment_man, comment_detail,
      insert_time)
    values (#{id,jdbcType=INTEGER}, #{commentMan,jdbcType=INTEGER}, #{commentDetail,jdbcType=VARCHAR}, 
      #{insertTime,jdbcType=TIMESTAMP})
  </insert>
keyProperty="id"中的id对应实体中的主键

猜你喜欢

转载自www.cnblogs.com/malefeng/p/10625469.html