第一种
第一种办法较为简单,就是在<insert>
标签内添加keyProperty
属性,就像下面这样
<insert id="insert" parameterType="com.musoulee.myseckill.entity.ItemStock" keyProperty="id">
insert into item_stock (id, item_id, stock)
values (#{id,jdbcType=INTEGER}, #{itemId,jdbcType=CHAR}, #{stock,jdbcType=INTEGER})
</insert>
第二种
第二种办法是在insert
标签内嵌套selectKey
标签,并将其order
属性设置为After
或者Before
来控制主键回填的时机。
<insert id="insert" parameterType="com.musoulee.myseckill.entity.Promotion">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
select last_insert_id()
</selectKey>
insert into promotion (id, name, start_time,
end_time, item_id, promotion_price)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{startTime,jdbcType=TIMESTAMP},
#{endTime,jdbcType=TIMESTAMP}, #{itemId,jdbcType=CHAR}, #{promotionPrice,jdbcType=DOUBLE})
</insert>
注意这个地方selectKey
标签一定要加返回类型的属性,否则会报如下错误
A query was run and no Result Maps were found for the Mapped Statement "xxx", It's likely that neither a Result Type nor a Result Map was specified.