Mybatis使用selectKey返回插入数据的id

注解类型

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.SelectKey;

public interface KeyAnnoMapper { 
        /*
         * statement="select last_insert_id()":表示定义的子查询语句
         * before=false:表示在插入之前执行,由于是自增主键,所以为false
         * keyColumn="id":插入数据以后,要返回的内容在数据表中对应的字段名称
         * resultType=long.class:表示返回值得类型
         * keyProperty="id":指定返回的id映射到bean中的哪个属性,这里类属性也叫id
         */
        //使用注解
	@Insert("insert into order_info(user_id, goods_id, goods_name, goods_count, goods_price, order_channel, status, create_date)
	values(#{userId}, #{goodsId}, #{goodsName}, #{goodsCount}, #{goodsPrice}, #{orderChannel},#{status},#{createDate} )")
	@SelectKey(keyColumn="id", keyProperty="id", resultType=long.class, 
		before=false, statement="select last_insert_id()")
	public long insert(OrderInfo orderInfo);
}

XML类型

<insert id="insert" parameterType="OrderInfo">
     insert into order_info(user_id, goods_id, goods_name, goods_count, goods_price, order_channel, status, create_date)
	values(#{userId}, #{goodsId}, #{goodsName}, #{goodsCount}, #{goodsPrice}, #{orderChannel},#{status},#{createDate} ))
        
    <selectKey keyColumn="id" keyProperty="id" order="AFTER" resultType="long">
      select last_insert_id()
    selectKey>
insert>

语义等同于注解类型

获取id

为什么执行这个sql后,一直返回1?因为返回的值是受影响行数,而不是id,id被注入到bean里

应该这么获取

long result = orderDao.insert(orderInfo);
long orderId = orderInfo.getId();

我插入数据时插入的是一个bean,这个bean的类型就是上面我们提到的parameterType的值,插入前它的id是空。

当我们执行插入后,返回插入的结果result,插入成功result=1,插入失败result=0,这就是为什么结果一直为1了,因为返回的结果根本不是我们需要的id,返回的id其实已经映射到了我们插入的bean中,我们只要通过它的get方法就可以得到了:orderInfo.getId();

你可能感兴趣的:(MyBatis)