Mybatis+mysql之insert返回主键id

在业务处理中,我们经常会需要新插入数据的主键id,使用mybatis的话,在mapper.xml中加入下述配置,即可在新数据插入成功后获取其主键Id

  1. 配置:【keyProperty=”id” useGeneratedKeys=”true”】,其中id是插入表的主键id
id="insertSelective" parameterType="com.jaychou.www.entity.GoodsInfo" keyProperty="id" useGeneratedKeys="true"> 
    insert into goods_info_table
    "(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      if>
      <if test="goodsCode != null">
        goods_code,
      if>
      <if test="goodsName != null">
        goods_name,
      if>
    
    "values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      if>
      <if test="goodsCode != null">
        #{goodsCode,jdbcType=VARCHAR},
      if>
      <if test="goodsName != null">
        #{goodsName,jdbcType=VARCHAR},
      if>  
      

在mapper.xml配置好后,代码实现流程大致如下:

  1. 把goodsInfo这个对象插入到数据库中:int id = goodsInfoMapper.insertSelective(goodsInfo);

  2. 得到新数据的主键Id: int goodsId = goodsInfo.getId();

你可能感兴趣的:(mybatis)