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