mybatis批量插入

批量插入指的是执行一次sql语句,提高插入效率

下面提供mysql和oracle数据库的方法:

mysql:

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.etoak.dao.BatchInsertTest">
    <insert id="batchInsert" parameterType="java.util.List">
        insert into student (name, password) values
        <foreach collection="list" item="item" index="index" separator=",">
            (#{item.name},
            #{item.password} )
        </foreach>
    </insert>
</mapper>

oracle:

<insert id="batchInsert" parameterType="java.util.List">
    insert into student (name, password) 
    <foreach close=")" collection="list" item="item" index="index"
        open="(" separator="union">
        select
        #{item.name,jdbcType=VARCHAR},
        #{item.password,jdbcType=VARCHAR}
        from dual
    </foreach>
</insert>

接口:

public int batchInsert(List<Student> students);

测试:

List<Student> students = new ArrayList<Student>();
        students.add(new Student(10,"a","b"));
        students.add(new Student(11,"a","b"));
        students.add(new Student(12,"a","b"));
        students.add(new Student(13,"a","b"));
        students.add(new Student(14,"a","b"));
        students.add(new Student(15,"a","b"));
        batchInsertTest.batchInsert(students);

你可能感兴趣的:(mybatis,批量插入)