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

1.

useGeneratedKeys="true" keyProperty="id"

 /*id对应属性值*/
  insert into pms_comment_replay
  
    
      comment_id,
    
  
  
    
      #{commentId,jdbcType=BIGINT},
    
  

2.


    select last_insert_id();


  
    SELECT LAST_INSERT_ID()    /*order的值可以为BEFORE,插入前获取;AFTER,插入后获取;且区分大小写,只能是大写,不可为小写*/
  
  insert into pms_comment_replay
  
    
      comment_id,
    
  
  
    
      #{commentId,jdbcType=BIGINT},
    
  
@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默认值  dao层不要使用@param起别名


    
        insert into pms_full_reduction (id, full_price, reduce_price)
        values
        
            (null, #{obj.fullPrice}, #{obj.reducePrice})
        
    

mybatis获取自增主键插入数据后id值的两种方式_第1张图片

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

 private String setfullReductionList(List 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(","));
    }

 

你可能感兴趣的:(java)