mybatis获取自增主键插入数据后id值的两种方式

1.

useGeneratedKeys="true" keyProperty="id"

<insert id="insertCommentReplay" parameterType="com.macro.mall.dto.PmsBusCommentReplay"  
useGeneratedKeys="true" keyProperty="id"> /*id对应属性值*/
  insert into pms_comment_replay
  <trim prefix="(" suffix=")" suffixOverrides="," >
    <if test="commentId != null" >
      comment_id,
    </if>
  </trim>
  <trim prefix="values (" suffix=")" suffixOverrides="," >
    <if test="commentId != null" >
      #{commentId,jdbcType=BIGINT},
    </if>
  </trim>
</insert>

2.

<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
    select last_insert_id();
</selectKey>

<insert id="insertCommentReplay" parameterType="com.macro.mall.dto.PmsBusCommentReplay">
  <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
    SELECT LAST_INSERT_ID()    /*order的值可以为BEFORE,插入前获取;AFTER,插入后获取;且区分大小写,只能是大写,不可为小写*/
  </selectKey>
  insert into pms_comment_replay
  <trim prefix="(" suffix=")" suffixOverrides="," >
    <if test="commentId != null" >
      comment_id,
    </if>
  </trim>
  <trim prefix="values (" suffix=")" suffixOverrides="," >
    <if test="commentId != null" >
      #{commentId,jdbcType=BIGINT},
    </if>
  </trim>
</insert>
@Override
public PmsBusCommentReplay insertCommentReplay(PmsBusCommentReplay param) {
    param.setCreateTime(new Date());
    param.setType(1);
    int count=commentDao.insertCommentReplay(param); //插入方法
    param.setId(param.getId()); //插入成功后获取插入后的id值,存入返回
    if(count>0){
        return param;
    }
    return null;
}

3.批量插入,返回自增主键  list,collection默认值  dao层不要使用@param起别名

<!--批量插入满减记录-->
    <insert id="insertFullReduction" keyProperty="id" useGeneratedKeys="true"
            parameterType="java.util.List">
        insert into pms_full_reduction (id, full_price, reduce_price)
        values
        <foreach collection="list" item="obj" separator=",">
            (null, #{obj.fullPrice}, #{obj.reducePrice})
        </foreach>
    </insert>

3.1 遍历之前传入的List集合 ,getId就能得到id

 private String setfullReductionList(List<FullReduction> fullReductionList) {
        discountMapper.insertFullReduction(fullReductionList);//批量插入满减记录
        StringBuffer sb=new StringBuffer();
        for (FullReduction reduction:fullReductionList){
            Long id = reduction.getId();
            sb.append(id).append(",");
        }
        return sb.toString().substring(0,sb.lastIndexOf(","));
    }

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值