原创

Mybatis逆向工程之插入数据返回该记录id

在生成表的加入如下代码即可

<table schema="" tableName="表名" >
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>

使用的时候
如下

    public TDataAccount insertTDataAccountAndBackId() {
    TDataAccount record = new TDataAccount();
    record.setCreateTime(new Date());
    accountMapper.insertSelective(record );
    return record;
}

可以返回这条记录,这个记录里面就包含插入这条数据的Id
就是这么简单!
如果不是逆向工程可以按照下面的例子

 <insert id="insertSelective" parameterType="com.TDataAccount" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
    insert into t_data_account
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="totalMoney != null" >
        total_money,
      </if>
      <if test="createTime != null" >
        create_time,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="totalMoney != null" >
        #{totalMoney,jdbcType=DOUBLE},
      </if>
      <if test="createTime != null" >
        #{createTime,jdbcType=TIMESTAMP},
      </if>
    </trim>
    <selectKey resultType="int" keyProperty="id" order="AFTER">
        SELECT LAST_INSERT_ID()
    </selectKey>
  </insert>

重点在

useGeneratedKeys="true" keyColumn="id" keyProperty="id"
和
 <selectKey resultType="int" keyProperty="id" order="AFTER">
        SELECT LAST_INSERT_ID()
    </selectKey>

file
插入数据之后,mybatis会把id放到这个实体中,你就可以直接在这个实体获取id了。

正文到此结束(点击广告是对作者最大的支持)