ibatis插入时获取自增主键的方式

(1)对象作为参数执行插入

 <insert id="insert" parameterType="Person">

         insert ignore into tb_person_${tbIndex} (uid,name )

         values(#{person.uid,jdbcType=INTEGER},#{person.name,jdbcType=VARCHAR})

</insert>

此时,如果表中有和属性对应的id字段,在插入动作返回后,会同时将自增主键写入id

(2)当不以对象作为parameterType时,可以添加keyProperty属性

 <insert id="insert" parameterType="Person" useGeneratedKeys="true" keyProperty="id">
        insert into person(uid,name) values(#{uid},#{name})
    </insert>

(3)当不以对象作为parameterType时,使用selectKey取

<insert id="insert" parameterType="Person">

        <selectKey keyProperty="id" resultType="int">
            select LAST_INSERT_ID()
        </selectKey>
        insert into person(uid,name) values(#{uid},#{name})

    </insert>

但方法(3)存在问题,在并发量大的时候,如果在程序和DB之间存在其他的中间件,导致selectKey和insert拿到的可能并不是同一个DBconnection,最终取得的id可能并不是本次执行插入操作的id

猜你喜欢

转载自xiaoxiaoxuanao.iteye.com/blog/2314157
今日推荐