MyBatis-批量操作(MySQL)

MyBatis-批量操作(MySQL)

需求:批量添加员工

映射文件:



<mapper namespace="com.mybatis.dao.EmployeeMapperDynamicSQL">
	
	
    
	
	
	
	
	
	 
	<insert id="addEmps">
		<foreach collection="emps" item="emp" separator=";">
			insert into tbl_employee(last_name,email,gender,d_id)
			values(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
		foreach>
	insert>
 mapper>

测试文件:

package com.mybatis.test;
//省略import引包
public class MyBatisTest {
     
	//获取SqlSessionfactory对象的方法
	public SqlSessionFactory getSqlSessionFactory() throws IOException {
     
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		return new SqlSessionFactoryBuilder().build(inputStream);
	}
	
	@Test
	public void testBatchSave() throws IOException{
     
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		SqlSession openSession = sqlSessionFactory.openSession();
		try{
     
			//测试MySQL使用foreach的批量插入
			EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
			List<Employee> emps = new ArrayList<>();
			emps.add(new Employee(null,"Lucky","Lucky.com","1",new Department(1)));
			emps.add(new Employee(null,"Helen","helen.com","1",new Department(1)));
			emps.add(new Employee(null,"Elieen","Eileen.com","1",new Department(1)));
			System.out.println(emps);
			mapper.addEmps(emps);
			
			//增删改必须提交事务!!!
			openSession.commit();

		}finally{
     
			openSession.close();
		}
		
	}
}

MySql数据库的批量操作不同于Oracle数据库,Oracle不支持values(),(),(),在Oracle下进行批量操作可以利用中间表

你可能感兴趣的:(Java框架,MyBatis,批量操作,批量保存数据,mysql)