mybatis批量插入生成重复的uuid主键

时间:2018-03-29 03:56:07

标签: insert mybatis batch-insert

当我插入单个记录时:

<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>

但我想插入一个列表,如何生成uuid,如上面的单个插入???

 <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>

1 个答案:

答案 0 :(得分:0)

最简单的方法是将UUID生成器放在值块中:

<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>