mybatis动态sql之使用foreach进行批量插入的两种方式

EmployeeMapperDynamicSql.java

package com.gong.mybatis.mapper;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Param;

import com.gong.mybatis.bean.Employee;

public interface EmployeeMapperDynamicSql {
    public List<Employee> getEmpByConditionIf(Employee employee);

    public void addEmp(@Param("emps") List<Employee> employee);
}

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.gong.mybatis.mapper.EmployeeMapperDynamicSql">
    <!-- 查询,要查那个就带上那个条件 -->
    <select id="getEmpByConditionIf" resultType="com.gong.mybatis.bean.Employee">
        select * from tbl_employee
        <where>
            <choose>
                <when test="id!=null">
                    id=#{id}
                </when>
                <when test="lastName!=null">
                    last_name like #{lastName}
                </when>
                <when test="email!=null">
                    email=#{email}
                </when>
                <otherwise>
                </otherwise>
            </choose>
        </where>
    </select>

    <insert id="addEmp">
        insert into tbl_employee(last_name,gender,email,d_id)
        values
        <foreach collection="emps" item="emp" separator=",">
            (#{emp.lastName},#{emp.gender},#{emp.email},#{emp.dept.id})
        </foreach>
    </insert>
</mapper>

第一种方式如上所示:insert into tbl_employee(last_name,gender,email,d_id) values (?,?,?,?) , (?,?,?,?)

进行测试:

package com.gong.mybatis.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import com.gong.mybatis.bean.Department;
import com.gong.mybatis.bean.Employee;
import com.gong.mybatis.mapper.EmployeeMapperDynamicSql;

public class TestMybatis3 {

    public SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream is = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(is);
    }

    @Test
    public void test() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession openSession = sqlSessionFactory.openSession();
        try {
            EmployeeMapperDynamicSql mapper = openSession.getMapper(EmployeeMapperDynamicSql.class);
            List<Employee> emps = new ArrayList<>();
            Department d1 = new Department(1);
            Employee e1 = new Employee(null,"manwang","1","[email protected]",d1);
            Department d2 = new Department(2);
            Employee e2 = new Employee(null,"timo","0","[email protected]",d2);
            emps.add(e1);
            emps.add(e2);
            mapper.addEmp(emps);
            List<Employee> es = mapper.getEmpByConditionIf(new Employee());
            for(Employee e:es) {
                System.out.println(e);
            }
            openSession.commit();
        } finally {
            openSession.close();
        }

    }

}

输出结果:

DEBUG 01-21 21:16:38,183 ==>  Preparing: insert into tbl_employee(last_name,gender,email,d_id) values (?,?,?,?) , (?,?,?,?)   (BaseJdbcLogger.java:145)
DEBUG 01-21 21:16:38,261 ==> Parameters: manwang(String), 1(String), [email protected](String), 1(Integer), timo(String), 0(String), [email protected](String), 2(Integer)  (BaseJdbcLogger.java:145)
DEBUG 01-21 21:16:38,374 <==    Updates: 2  (BaseJdbcLogger.java:145)
DEBUG 01-21 21:16:38,385 ==>  Preparing: select * from tbl_employee   (BaseJdbcLogger.java:145)
DEBUG 01-21 21:16:38,386 ==> Parameters:   (BaseJdbcLogger.java:145)
DEBUG 01-21 21:16:38,430 <==      Total: 6  (BaseJdbcLogger.java:145)
Employee [id=1, lastName=dema, gender=1, email[email protected], dept=null]
Employee [id=2, lastName=jack, gender=1, email[email protected], dept=null]
Employee [id=3, lastName=小红, gender=0, email[email protected], dept=null]
Employee [id=4, lastName=小明, gender=0, email[email protected], dept=null]
Employee [id=5, lastName=manwang, gender=1, email[email protected], dept=null]
Employee [id=6, lastName=timo, gender=0, email[email protected], dept=null]

第二种方式需要在配置连接数据源时使用:

jdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true

然后在xml文件中:

    <insert id="addEmp">
        <foreach collection="emps" item="emp" separator=";">
            insert into tbl_employee(last_name,gender,email,d_id)
            values
            (#{emp.lastName},#{emp.gender},#{emp.email},#{emp.dept.id})
        </foreach>
    </insert> 

这种方式的sql形如:insert into tbl_employee(last_name,gender,email,d_id) values (?,?,?,?) ; insert into tbl_employee(last_name,gender,email,d_id) values (?,?,?,?)

结果:

DEBUG 01-21 21:34:32,747 ==>  Preparing: insert into tbl_employee(last_name,gender,email,d_id) values (?,?,?,?) ; insert into tbl_employee(last_name,gender,email,d_id) values (?,?,?,?)   (BaseJdbcLogger.java:145)
DEBUG 01-21 21:34:32,823 ==> Parameters: manwang(String), 1(String), [email protected](String), 1(Integer), timo(String), 0(String), [email protected](String), 2(Integer)  (BaseJdbcLogger.java:145)
DEBUG 01-21 21:34:32,889 <==    Updates: 1  (BaseJdbcLogger.java:145)
DEBUG 01-21 21:34:32,900 ==>  Preparing: select * from tbl_employee   (BaseJdbcLogger.java:145)
DEBUG 01-21 21:34:32,902 ==> Parameters:   (BaseJdbcLogger.java:145)
DEBUG 01-21 21:34:32,966 <==      Total: 8  (BaseJdbcLogger.java:145)
Employee [id=1, lastName=dema, gender=1, email[email protected], dept=null]
Employee [id=2, lastName=jack, gender=1, email[email protected], dept=null]
Employee [id=3, lastName=小红, gender=0, email[email protected], dept=null]
Employee [id=4, lastName=小明, gender=0, email[email protected], dept=null]
Employee [id=5, lastName=manwang, gender=1, email[email protected], dept=null]
Employee [id=6, lastName=timo, gender=0, email[email protected], dept=null]
Employee [id=7, lastName=manwang, gender=1, email[email protected], dept=null]
Employee [id=8, lastName=timo, gender=0, email[email protected], dept=null]

原文地址:https://www.cnblogs.com/xiximayou/p/12226003.html

时间: 2024-10-05 05:04:47

mybatis动态sql之使用foreach进行批量插入的两种方式的相关文章

【ADO.NET-中级】百万级数据的批量插入的两种方法测试

在SQL Server 中插入一条数据使用Insert语句,但是如果想要批量插入一堆数据的话,循环使用Insert不仅效率低,而且会导致SQL一系统性能问题.下面介绍SQL Server支持的两种批量数据插入方法:Bulk和表值参数(Table-Valued Parameters). 运行下面的脚本,建立测试数据库和表值参数. --Create DataBase create database BulkTestDB; Go use BulkTestDB; go --Create Table Cr

Hibernate批量删除的两种方式

第一种:使用Hibernate映射类对对象进行封装操作 --------------------------------------------------------------------------- @Override    public boolean deleteTrainee(long[] id) {        try {            Session session = HibernateSessionFactory.getSession();            

MyBatis动态SQL————MyBatis动态SQL标签的用法

1.MyBatis动态SQL MyBatis 的强大特性之一便是它的动态 SQL,即拼接SQL字符串.如果你有使用 JDBC 或其他类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句有多么痛苦.拼接的时候要确保不能忘了必要的空格,还要注意省掉列名列表最后的逗号.利用动态 SQL 这一特性可以彻底摆脱这种痛苦. 通常使用动态 SQL 不可能是独立的一部分,MyBatis 当然使用一种强大的动态 SQL 语言来改进这种情形,这种语言可以被用在任意的 SQL 映射语句中. 动态 SQL 元素和

mybatis 动态SQL查询总结

背景 ××项目需要提供系统部分函数第三方调用接口,基于安全性和避免暴露数据库表信息的基础上进行函数接口的设计,根据第三方调用身份的权限提供某张表的自定义集合.本项目基于mybatis的持久层框架,支持定制化的SQL,这样可以避免拼接sql语句的痛苦.例如拼接时要确保不能添加空格,还要注意去掉列表的最后一个列名的都逗号.基于OGNL的表达式的mybatis框架可以彻底解决这种痛苦. 动态返回mysql某张表指定列的名字,类型和注释 <select id="queryColumns"

mybatis动态sql以及分页

1.mybatis动态sql 2.模糊查询 3.查询返回结果集的处理 4.分页查询 5.特殊字符处理 1.mybatis动态sql If.trim.foreach If 标签判断某一字段是否为空 <select id="list4" resultType="java.util.Map" parameterType="java.util.Map"> select * from t_mvc_book <where> <i

MyBatis动态SQL小结

p.MsoNormal,li.MsoNormal,div.MsoNormal { margin: 0cm; margin-bottom: .0001pt; text-align: justify; font-size: 10.5pt; font-family: 等线 } .MsoChpDefault { font-family: 等线 } div.WordSection1 { } ol { margin-bottom: 0cm } ul { margin-bottom: 0cm } Mybati

mybatis实战教程(mybatis in action)之八:mybatis 动态sql语句

mybatis 的动态sql语句是基于OGNL表达式的.可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类:1. if 语句 (简单的条件判断)2. choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中的choose 很类似.3. trim (对包含的内容加上 prefix,或者 suffix 等,前缀,后缀)4. where (主要是用来简化sql语句中where条件判断的,能智能的处理 a

用Groovy模板写MyBatis动态SQL

MyBatis动态SQL简介 MyBatis有个强大的功能,动态SQL.有了这个功能,定义在Mapper里的SQL语句,就不必是静止不变的了,而是可以根据传入的参数,动态调整.下面是MyBatis官方文档里的一个if语句的例子: <select id="findActiveBlogWithTitleLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = 'ACTIVE' <if test=

Mybatis 动态sql(转载)

原文地址:http://www.cnblogs.com/dongying/p/4092662.html 传统的使用JDBC的方法,相信大家在组合复杂的的SQL语句的时候,需要去拼接,稍不注意哪怕少了个空格,都会导致错误.Mybatis的动态SQL功能正是为了解决这种问题, 其通过 if, choose, when, otherwise, trim, where, set, foreach标签,可组合成非常灵活的SQL语句,从而提高开发人员的效率.下面就去感受Mybatis动态SQL的魅力吧: 1