MyBatis插入语句获取主键id

来源:互联网 发布:蓝牙虚拟串口软件 编辑:程序博客网 时间:2024/05/14 19:49

解决问题:insert后需要用到自动生成的主键"id"

解决方法:

   
    <!-- 直接写到insert语句中 -->    <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">              SELECT LAST_INSERT_ID()    </selectKey>
在外面直接用  对象.getId 获得返回的值


使用示例:

<insert id="insertSelective" parameterType="po.TTask">    <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">          SELECT LAST_INSERT_ID()    </selectKey>    insert into t_task    <trim prefix="(" suffix=")" suffixOverrides=",">      <if test="id != null">        id,      </if>      <if test="username != null">        username,      </if>      <if test="stat != null">        stat,      </if>      <if test="ts != null">        ts,      </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="stat != null">        #{stat,jdbcType=INTEGER},      </if>      <if test="ts != null">        #{ts,jdbcType=TIMESTAMP},      </if>    </trim>  </insert>



原创粉丝点击