MyBatis动态sql_foreach下foreach批量插入两种方式

MyBatis动态sql_foreach下foreach批量插入两种方式


EmployeeMapperDynamicSQL.java

package com.cn.mybatis.dao;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.cn.zhu.bean.Employee;

public interface  EmployeeMapperDynamicSQL {
		
	public void addEmps(@Param("emps")List emps);
}

EmployeeMapperDynamicSQL.xml (两种批量保存方式)




  
	
	
	
	   
	  	 insert into tbl_employee(last_name,email,gender,d_id)
	   values(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
	   
	

这种保存方式(必须在mysql中开启,一次执行多条语句)


	   
	  	 insert into tbl_employee(last_name,email,gender,d_id)
	   values(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
	   
	
在资源文件这里加入这条语句


dbconfig.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true
jdbc.username=root
jdbc.password=root

测试方法

@Test
	public void testBatchSave() throws Exception{
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
	    SqlSession openSession = sqlSessionFactory.openSession();
	    try {
	    	EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
	        List  	emps=new ArrayList();
	        emps.add(new Employee(null, "小王", "小@qq.com", "1",new Department(1)));
	        emps.add(new Employee(null, "张三", "张三@qq.com", "0",new Department(1)));
	        mapper.addEmps(emps);
	        openSession.commit();
	    } catch (Exception e) {
			// TODO: handle exception
	    	openSession.close();
	    	e.printStackTrace();
		}
	}

测试结果

MyBatis动态sql_foreach下foreach批量插入两种方式_第1张图片

更多文章请关注微信公众号:

MyBatis动态sql_foreach下foreach批量插入两种方式_第2张图片

你可能感兴趣的:(MyBatis入门,MyBatis框架的学习专栏)