mybatis插入数据时,自动获取主键的自增id

首先int i = userMapper.insertSelective(user),这里返回的并不是主键自增id,而是成功插入的条数。如果想获取主键自增id,除了插入记录之后再查询之外,也可以使用mybatis提供的两种方式:
一是mybatis自动生成的sql语句:

  <insert id="insertSelective" parameterType="cn.tencent.eee.aaa.dao.model.User">
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="name != null">
        name,
      </if>
      <if test="createBy != null">
        create_by,
      </if>
      <if test="updateBy != null">
        update_by,
      </if>
      <if test="sysCtime != null">
        sys_ctime,
      </if>
      <if test="sysUtime != null">
        sys_utime,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="createBy != null">
        #{createBy,jdbcType=VARCHAR},
      </if>
      <if test="updateBy != null">
        #{updateBy,jdbcType=VARCHAR},
      </if>
      <if test="sysCtime != null">
        #{sysCtime,jdbcType=TIMESTAMP},
      </if>
      <if test="sysUtime != null">
        #{sysUtime,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>

二是在insert标签加属性,是否使用 useGeneratedKeys 开关为true,keyProperty对应的就是要返回的字段名称:

  <insert id="insertSelective" parameterType="cn.tencent.eee.aaa.dao.model.User" useGeneratedKeys="true" keyProperty="id">
  </insert>
注意:

1.通过以上两种方式获取自增id时,会直接赋值到领域模型的实体id中;

Integer i = user.getId;// i == null
if(userMapper.insertSelective(user) > 0){//如果插入成功
   i = user.getId;//i为主键自增id
}

2.insert标签里如果有多条insert语句,那么返回的则是最后一条insert语句的自增id。

参考:https://chenyi84.iteye.com/blog/2197076

猜你喜欢

转载自blog.csdn.net/weixin_33747129/article/details/87485099