- 背景
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對應實體中的主鍵