介绍:MyBatis批量插入数据,原理就是在xml文件中添加 foreach 语句,然后MyBatis自动在values后面添加多个括号;
XML文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sblueice.mapper.UploadMapper">
<resultMap id="TestUserResult" type="com.sblueice.entity.TestUser">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="sex" property="sex"/>
<result column="age" property="age"/>
</resultMap> <insert id="insertUser" parameterType="com.sblueice.entity.TestUser">
INSERT INTO testuser (name, sex, age)
VALUES
<foreach collection="list" item="it" separator=",">
(#{it.name},
#{it.sex},
#{it.age})
</foreach>
</insert> </mapper>
说明:
- mysql批量插入的限制是一次批量:1M
- 我这里插入的List,如上就好,如果是其他结构,查看这篇博客:http://www.cnblogs.com/admol/articles/4248159.html
- collection属性:
1.如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
2.如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
3.如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map
原文链接:https://www.cnblogs.com/java-zhao/p/5594795.html