Mybatis设置insert返回主键

<insert id="insertSelective" parameterType="xx.PayUser" useGeneratedKeys="true" keyProperty="id">

    insert into pay_user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        ID,
      </if>
      <if test="userName != null">
        USER_NAME,
      </if>
      <if test="password != null">
        PASSWORD,
      </if>
      <if test="phone != null">
        PHONE,
      </if>
      <if test="status != null">
        STATUS,
      </if>
      <if test="createTime != null">
        CREATE_TIME,
      </if>
      <if test="updateTime != null">
        UPDATE_TIME,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="userName != null">
        #{userName,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="phone != null">
        #{phone,jdbcType=VARCHAR},
      </if>
      <if test="status != null">
        #{status,jdbcType=VARCHAR},
      </if>
      <if test="createTime != null">
        #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="updateTime != null">
        #{updateTime,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>

关键在于

useGeneratedKeys="true" keyProperty="id"

表示将返回的主键赋值给id字段,注意:这里返回的还是1,想要获取id需要使用payUser .getId()

PayUser payUser = new PayUser();
payUser.setUserName(userName);
payUser.setPhone(phone);
payUser.setPassword(SHA1.getInstance().getMySHA1Code(pwd));
payUser.setStatus(EnumConstants.UserStatus.normal.value());
int i = payUserMapper.insertSelective(payUser);
if(i != 1){
    throw new JpfException(JpfErrorInfo.DAL_ERROR, "添加失败");
}

你可能感兴趣的:(Mybatis)