方法一:
<insert id="batchInsert" parameterType="java.util.List">
INSERT ALL
<foreach collection="list" item="item" index="index">
INTO TEST
(
USERNAME,
PASSWORD
) VALUES
(
#{item.userName, jdbcType=NUMERIC},
#{item.password, jdbcType=VARCHAR}
)
</foreach>
SELECT 1 FROM DUAL
</insert>方法二:<insert id="batchInsert" parameterType="java.util.List">
INSERT INTO TEST
(
USERNAME,
PASSWORD
)
<foreach collection="list" item="item" index="index" open="(" separator="union all" close=")">
SELECT
#{item.userName, jdbcType=NUMERIC},
#{item.password, jdbcType=VARCHAR}
FROM DUAL
</foreach>
</insert>
本文介绍了使用MyBatis进行批量数据插入的两种方法。第一种方法通过直接构造SQL语句实现多条记录的同时插入;第二种方法利用UNION ALL结合子查询的方式实现批量插入。这两种方法均可有效提高数据插入效率。

被折叠的 条评论
为什么被折叠?



