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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM