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<Employee> emps);
}

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

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cn.mybatis.dao.EmployeeMapperDynamicSQL">
  
	<!-- 批量保存 -->
	<!-- public void addEmps(@Param("emps")List<Employee> emps); --><!--
	<insert id="addEmps">
	   insert into tbl_employee(last_name,email,gender,d_id)
	   values 
	   <foreach collection="emps" item="emp" separator=",">
	     (#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
	   </foreach>	 
	</insert>
	-->
	<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>

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

<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>
在资源文件这里加入这条语句


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<Employee>  	emps=new ArrayList<Employee>();
	        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();
		}
	}

测试结果


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


发布了273 篇原创文章 · 获赞 480 · 访问量 115万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 程序猿惹谁了 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览