1.在productMapper.xml中的insert语句后加上如下语句:
/*获取刚插入的数据的自增ID*/
<selectKey keyProperty="productId" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
整体效果如下:
<insert id="insert" parameterType="com.lzw.emall.bean.Product" >
insert into product (product_id, product_name, product_price,
product_image, product_info, category_id,
is_hot, puton_time, product_store
)
values (#{productId,jdbcType=INTEGER}, #{productName,jdbcType=VARCHAR}, #{productPrice,jdbcType=DECIMAL},
#{productImage,jdbcType=VARCHAR}, #{productInfo,jdbcType=VARCHAR}, #{categoryId,jdbcType=INTEGER},
#{isHot,jdbcType=INTEGER}, #{putonTime,jdbcType=TIMESTAMP}, #{productStore,jdbcType=INTEGER}
)
/*获取刚插入的数据的自增ID*/
<selectKey keyProperty="productId" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
</insert>
此时执行productMapper.insert(product),你肯定认为这个返回的是你想要的id,其实这个返回的是影响的行数,如果要ID那么就到实体product里面去getProductId()就可以了 。
也就是说mybatis把得到的id封装到实体的ID属性里面去了。比如:你调用productMapper.insert(product)来保存, mybatis会将id封装到product中。
————————————————
版权声明:本文为CSDN博主「中午no睡」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_43538993/article/details/104346240