一、前言
当我们使用MyBatis一次性插入多条数据时候也可以使用foreach标签,本文我们将介绍MySQL中使用MyBatis批量插入数据的两种方式。
二、案例
①第一种方式
修改EmpMapper文件,增加batchSave方法
/** * 批量插入数据 * @param empList */ public void batchSave(List<Emp> empList);
修改EmpMapper.xml文件
<insert id="batchSave"> into t_emp(emp_name,emp_email,dept_id) VALUES <foreach collection="list" item="emp" separator=","> (#{emp.empName}, #{emp.empEmail}, #{emp.deptId}) </foreach> </insert>
修改MyBatis测试类,增加测试方法testBatchSave
@Test public void testBatchSave() throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); try { EmpMapper mapper = openSession.getMapper(EmpMapper.class); List<Emp> empList = new ArrayList<Emp>(); empList.add(new Emp(null,"Lucy","[email protected]",1)); empList.add(new Emp(null,"Lily","[email protected]",2)); empList.add(new Emp(null,"Lizy","[email protected]",3)); mapper.batchSave(empList); //别忘了事务最后要提交 openSession.commit(); } finally { openSession.close(); } }
测试控制台打印结果如下
2017-08-13 12:47:42,489 [main] [com.queen.mybatis.mapper.EmpMapper.batchSave]-[DEBUG] ==> Preparing: insert into t_emp(emp_name,emp_email,dept_id) VALUES (?, ?, ?) , (?, ?, ?) , (?, ?, ?) 2017-08-13 12:47:42,547 [main] [com.queen.mybatis.mapper.EmpMapper.batchSave]-[DEBUG] ==> Parameters: Lucy(String), [email protected](String), 1(Integer), Lily(String), [email protected](String), 2(Integer), Lizy(String), [email protected](String), 3(Integer) 2017-08-13 12:47:42,549 [main] [com.queen.mybatis.mapper.EmpMapper.batchSave]-[DEBUG] <== Updates: 3
由上面打印SQL可知,MySQL支持 insert into table values(?,?,?),(?,?,?) 这种语法
②第二种方式
修改EmpMapper.xml文件
测试控制台打印结果报错
org.apache.ibatis.exceptions.PersistenceException: ### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'insert into t_emp(emp_name,emp_email,dept_id) VALUES ('Lily123', 'Lily123@s' at line 4 ### The error may involve defaultParameterMap ### The error occurred while setting parameters ### SQL: insert into t_emp(emp_name,emp_email,dept_id) VALUES (?, ?, ?) ; insert into t_emp(emp_name,emp_email,dept_id) VALUES (?, ?, ?) ; insert into t_emp(emp_name,emp_email,dept_id) VALUES (?, ?, ?) ### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'insert into t_emp(emp_name,emp_email,dept_id) VALUES ('Lily123', 'Lily123@s' at line 4
报错信息说:不支持这种一次性插入多条的语法,这时候我们要怎么处理?
这里,需要修改mysql的连接参数allowMultiQueries=true
再次测试一下,成功。这种方式也适合于其他的批量操作,例如更新,删除;
=======欢迎大家拍砖,小手一抖,多多点赞哟!=======
版权声明:本文为博主原创文章,允许转载,但转载必须标明出处。