在 jdbc批量插入中
- Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=UTF-8&useServerPrepStmts=false&rewriteBatchedStatements=true","root","root");
- connection.setAutoCommit(false);
- PreparedStatement ps = connection.prepareStatement(
- "insert into t_user(name, ..) values(?)");
- for (int i = 0; i < stuNum; i++) {
- ps.setString(1,name);
- ps.addBatch();
- }
- ps.executeBatch();
- connection.commit();
- connection.close();
mybatis mapper
- <insert id="batchInsert" parameterType="java.util.List">
- insert into USER (id, name) values
- <foreach collection="list" item="model" index="index" separator=",">
- (#{model.id}, #{model.name})
- foreach>
- insert>
居然是 把 list 全部追加到 insert 语句后面,最后弄得语句很长:
INSERT INTO `table1` (`field1`, `field2`)
VALUES ("data1", "data2"),
("data1", "data2"),
("data1", "data2"),
("data1", "data2"),
("data1", "data2");
导致编译执行时间过长,所以mybatis 批量插入,需要控制在50条以内,
数据很多,mybatis 推荐写法:
- SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH);
- try {
- UserInfoMapper mapper = session.getMapper(UserInfoMapper.class);
- List
records = getRecordsToInsert(); -
- BatchInsert
batchInsert = insert(records) - .into(userInfoTable)
- .map(id).toProperty("id")
- .map(firstName).toProperty("firstName")
- .map(lastName).toProperty("lastName")
- .map(birthDate).toProperty("birthDate")
- .map(employed).toProperty("employed")
- .map(occupation).toProperty("occupation")
- .build()
- .render(RenderingStrategy.MYBATIS3);
-
- batchInsert.insertStatements().stream().forEach(mapper::insert);
-
- session.commit();
- } finally {
- session.close();
- }