• 背景

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对应实体中的主键

转载于:https://www.cnblogs.com/malefeng/p/10625469.html

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐