1. 程式人生 > >mybatis 實現插入一條記錄的同時,並返回主鍵自增策略是自增生成的主鍵ID

mybatis 實現插入一條記錄的同時,並返回主鍵自增策略是自增生成的主鍵ID

<insert id="insert" parameterType="com.mmall.pojo.Shipping" useGeneratedKeys="true" keyProperty="id">
    insert into mmall_shipping (id, user_id, receiver_name, 
      receiver_phone, receiver_mobile, receiver_province, 
      receiver_city, receiver_district, receiver_address, 
      receiver_zip, create_time, update_time
      )
    values (#{id,jdbcType=INTEGER}, #{userId,jdbcType=INTEGER}, #{receiverName,jdbcType=VARCHAR}, 
      #{receiverPhone,jdbcType=VARCHAR}, #{receiverMobile,jdbcType=VARCHAR}, #{receiverProvince,jdbcType=VARCHAR}, 
      #{receiverCity,jdbcType=VARCHAR}, #{receiverDistrict,jdbcType=VARCHAR}, #{receiverAddress,jdbcType=VARCHAR}, 
      #{receiverZip,jdbcType=VARCHAR}, now() ,now()
      )
  </insert>

在insert節點加上如下配置 是否使用 useGeneratedKeys 開關為true,keyProperty對應的就是要返回的欄位名稱

useGeneratedKeys="true" keyProperty="id"

在成功的插入資料後,會把設定的主鍵id填充到該shipping物件中要拿到id的值就可以直接使用shipping.getId();

public ResponseService add(Shipping shipping,Integer userId){
        shipping.setUserId(userId);
        int resultCount  = shippingMapper.insert(shipping);
        if (resultCount > 0){
            Map result = Maps.newHashMap();
            result.put("shippingId",shipping.getId());
            return ResponseService.createBySuccess("新增地址成功",result);
        }else{
            return ResponseService.createByErrorMessage("新增地址失敗");
        }
    }