mybatis获取刚插入数据的ID

1.很多时候,sql的语句的住建都是逐渐递增的,mybatis给我们提供了获取ID的方法
2.代码,方法一
1.useGeneratedKeys=“true” keyProperty=“id”

  <insert id="insert" parameterType="com.yd.pojo.DemoUser" useGeneratedKeys="true" keyProperty="id" >
    insert into demo_user (id, name, age, 
      address, love)
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, 
      #{address,jdbcType=VARCHAR}, #{love,jdbcType=VARCHAR})
  </insert>

方法二

select LAST_INSERT_ID()

  <insert id="insertSelective" parameterType="com.yd.pojo.DemoUser" >
    <selectKey keyProperty="id" resultType="java.lang.Integer" order="AFTER">
      select LAST_INSERT_ID()
    </selectKey>
    insert into demo_user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="name != null" >
        name,
      </if>
      <if test="age != null" >
        age,
      </if>
      <if test="address != null" >
        address,
      </if>
      <if test="love != null" >
        love,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        #{age,jdbcType=INTEGER},
      </if>
      <if test="address != null" >
        #{address,jdbcType=VARCHAR},
      </if>
      <if test="love != null" >
        #{love,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>

3.运行结果
在这里插入图片描述

posted @ 2019-08-20 18:25  smileLS66  阅读(159)  评论(0编辑  收藏  举报