sessionFactory.openSession(ExecutorType.BATCH ); --推荐的写法
BATCH: 预编译SQL一次 ,其余DML 只需要设置参数值即可
insert into student(stuNo,stuName,stuAge,graName)
values(#{stuNo} , #{stuName},#{stuAge},#{graName})
没有BATCH:
预编译N次 ,每次DML都需要 执行完整的SQL
public static void addBatchStudents() throws IOException {
String resource = "conf.xml";
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sessionFactory
= new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sessionFactory.openSession( ExecutorType.BATCH);
StudentMapper studentMapper = session.getMapper(StudentMapper.class);//接口
long start = System.currentTimeMillis();
for(int i=0;i<100000;i++) {
Student stu = new Student((int)(Math.random()*9000) +1000, "abc", 44, "xx");
studentMapper.addStudent(stu);
}
long end = System.currentTimeMillis();
System.out.println(end-start);
session.commit();//手工提交
session.close();
}
不推荐的方式: 拼接SQL
oracle:批量插入
a. create table 表 select … from 旧表
b. insert into 表(…) select … from 表 ;
c. begin …(DML)… end ;
d. 数据泵、SQL Loader 、外部表
以 c. begin …(DML)… end ;为例
void addStudentOracle (List<Student> students) ;
<insert id="addStudentOracle" databaseId="oracle">
<foreach collection="list" open="begin" close="end ;" item="student">
insert into student(stuno,stuname) values(#{student.stuNo},#{student.stuName}) ;
</foreach>
</insert>
mysql:批量插入
insert into student(stuno,stuname) values(100,‘zsx’),(200,‘lsx’),(200,‘lsx’),(200,‘lsx’)… ;
void addStudentMySql (List<Student> students) ;
<insert id="addStudentMySql" databaseId="mysql">
insert into student(stuno,stuname) values
<foreach collection="list" item="student" separator="," close=";" >
(#{student.stuNo},#{student.stuName})
</foreach>
</insert>
还有这种语句所有数据都支持:
insert into … values(…);
insert into … values(…);
insert into … values(…);
insert into … values(…);
insert into … values(…);
insert into … values(…);
insert into … values(…);
以mysql为例演示:
void addStudentMySql2 (List<Student> students) ;
<insert id="addStudentMySql2" databaseId="mysql">
<foreach collection="list" item="student" >
insert into student(stuno,stuname) values(#{student.stuNo},#{student.stuName}) ;
</foreach>
</insert>
不过这样会导致语句中间有很多分号,所以mysql的链接地址要改一下:
注意mysql.url !!!
#mysql
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/mydb?allowMultiQueries=true
mysql.username=root
mysql.password=root
还有有种推荐的做法就是调用存储过程,存储函数实现批量增加!