insertmybatisbatch-insert

mybatis batch insert generating duplicate uuid primary key


when i insert single record:

<insert id="add" parameterType="SysUser">
    <selectKey keyProperty="id" resultType="String" order="BEFORE">
        select replace(uuid(),'-','') from dual
    </selectKey>
    insert into sys_user(id,user_name,user_email,user_info,user_password,create_time)
    values
    (#{id,jdbcType=VARCHAR},
    #{userName,jdbcType=VARCHAR},
    #{userEmail,jdbcType=VARCHAR},
    #{userInfo,jdbcType=VARCHAR},
    #{userPassword,jdbcType=VARCHAR},
    #{createTime,jdbcType=TIMESTAMP})
</insert>

but i want to insert a list, how can i generate the uuid like the single insert above???

 <insert id="addSysUsers"  parameterType="List" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO sys_user(user_name,user_password,user_email)
        VALUES
        <foreach collection="sysUsers" item="sysUser" separator=",">
            (#{sysUser.userName,jdbcType=VARCHAR},#{sysUser.userPassword,jdbcType=VARCHAR},#{sysUser.userEmail,jdbcType=VARCHAR})
        </foreach>

    </insert>

Solution

  • The simplest way to do it is put the UUID generator in the values block:

    <insert id="add" parameterType="SysUser">
        insert into sys_user(id,user_name,user_email,user_info,user_password,create_time)
        values
        (replace(uuid(),'-',''), <!-- create uuid directly here --->
        #{userName,jdbcType=VARCHAR},
        #{userEmail,jdbcType=VARCHAR},
        #{userInfo,jdbcType=VARCHAR},
        #{userPassword,jdbcType=VARCHAR},
        #{createTime,jdbcType=TIMESTAMP})
    </insert>