MyBatis动态sql_foreach下foreach批量插入两种方式
程序员文章站
2022-05-25 17:02:32
...
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();
}
}
测试结果
更多文章请关注微信公众号: