mybatis批量保存

a:focus {
outline: thin dotted #333;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
a:hover {
outline: 0;
}
a:active {
outline: 0;
}
a:hover {
color: #005580;
text-decoration: underline;
}
blockquote small:before {
content: ‘\2014 \00A0‘;
}
q:before {
content: "";
}
q:after {
content: "";
}
blockquote:before {
content: "";
}
blockquote:after {
content: "";
}

mybatis批量保存

mybatis

批量保存

1、概述

mybatis 批量保存的时候,如果数据大于1000条,应该使用批量的形式进行处理数据;处理的不同的地方主要是在xml文件当中的配置信息;一种是使用java的for进行保存,另一种,是使用xml中的循环拼接sql来完成数据的插入;现在我们来对比两种方式的不同,以及执行效率;

2、 方法1:使用java的for循环来完成批量保存

1、打开批处理

session = sqlSessionFactory.openSession(ExecutorType.BATCH, true);

2、初始化数据

List<Student> preSaveStudent = initStudent();

3、执行批量插入

    for (int i = 0; i < preSaveStudent.size(); i++) {
            studentMapper.insert(preSaveStudent.get(i));
        }

4、事务提交

    session.commit();

代码实例:

@Test
    public void BatchSave() throws IOException{
        org.apache.ibatis.logging.LogFactory.useStdOutLogging();
        Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(reader);
        reader.close();
        SqlSession session = null;
        //1、打开批处理
        session = sqlSessionFactory.openSession(ExecutorType.BATCH, true);
        StudentMapper studentMapper = (StudentMapper) session.getMapper(StudentMapper.class);
        Map<String, Object> params = new HashMap<String,Object>();
        List<Student> students = studentMapper.queryStudentAndTeacher(params);

        //2、初始化数据
        List<Student> preSaveStudent = initStudent();
        Date first = new Date();  

        //3、执行批量插入
        for (int i = 0; i < preSaveStudent.size(); i++) {
            studentMapper.insert(preSaveStudent.get(i));
        }
        //4、事务提交
        session.commit();
        System.out.println("first quest costs:"+ (new Date().getTime()-first.getTime()) +" ms");
    }
    /**
     * 打印学生信息
     * @author thero
     * @param students
     */
    public void printStudent(List<Student> students){
        for (Student student : students) {
            System.out.println(student.getId() + student.getTeacher().getName());
        }
    }

    /**
     * 初始化参数;用于测试保存内容;
     * @author thero
     * @return List<Student>
     *  student集合内容
     */
    public List<Student> initStudent(){
        List<Student> students = new ArrayList<Student>();
        for(int i = 0 ;i < 1000;i++){
            Student student = new Student();
            student.setGender("男"+i);
            student.setGrade("100"+i);
            student.setMajor("软件技术"+i);
            student.setName("小哈哈"+i);
            student.setSupervisorId(1);
            students.add(student);
        }
        return students;
    }

其中xml的配置内容为:

 <insert id="insert" parameterType="com.cpp.core.common.entity.Student" >
    insert into student (id, name, gender,
      major, grade, supervisor_id
      )
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{gender,jdbcType=VARCHAR},
      #{major,jdbcType=VARCHAR}, #{grade,jdbcType=VARCHAR}, #{supervisorId,jdbcType=INTEGER}
      )
  </insert>

程序完成插入执行的时间为:

first quest costs:3267 ms

2.1 相关日志输出

Logging initialized using 'org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Openning JDBC Connection
Created connection 24166053.
Setting autocommit to true on JDBC Connection [[email protected]]
ooo Using Connection [[email protected]]
==>  Preparing: SELECT s.id, s.`name`, s.gender, s.major, s.grade, s.supervisor_id , t.id as tea_id, t.`name` as tea_name, t.gender as tea_gender, t.research_area as tea_research_area, t.title as tea_title FROM student s LEFT JOIN teacher t ON s.supervisor_id = t.id
==> Parameters:
<==    Columns: id, name, gender, major, grade, supervisor_id, id, name, gender, research_area, title
<==        Row: 1, 李林, 男, 计算机科学与技术, 2011, 1, 1, 刘老师, null, null, null
<==        Row: 2, 陈明, 男, 软件技术, 2012, 1, 1, 刘老师, null, null, null
<==        Row: 4, 陈明2, 男, 软件技术, 2012, 2, 2, 郝老师, 男, 无语, 五
ooo Using Connection [[email protected]170bea5]
==>  Preparing: insert into student (id, name, gender, major, grade, supervisor_id ) values (?, ?, ?, ?, ?, ? )
==> Parameters: null, 小哈哈0(String), 男0(String), 软件技术0(String), 1000(String), 1(Integer)
==> Parameters: null, 小哈哈0(String), 男0(String), 软件技术0(String), 1000(String), 1(Integer)
==> Parameters: null, 小哈哈1(String), 男1(String), 软件技术1(String), 1001(String), 1(Integer)
==> Parameters: null, 小哈哈2(String), 男2(String), 软件技术2(String), 1002(String), 1(Integer)
....
==> Parameters: null, 小哈哈999(String), 男999(String), 软件技术999(String), 100999(String), 1(Integer)
first quest costs:3267 ms

3、方法2 xml中循环学生的相关信息;

与方法1相比,在xml发生的变化较大的地方是xml,主要是在xml拼接了sql,下面是xml内容

  <insert id="batchInsert" parameterType="list">
      insert into student (id, name, gender,
      major, grade
      )
    values
     <foreach collection="list" item="item" index="index" separator=",">
         (null,#{item.name},#{item.gender},#{item.major},#{item.grade})
     </foreach>
  </insert>

我们查看执行输入内容

Logging initialized using 'org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Openning JDBC Connection
Created connection 13676443.
Setting autocommit to true on JDBC Connection [[email protected]]
ooo Using Connection [[email protected]]
==>  Preparing: SELECT s.id, s.`name`, s.gender, s.major, s.grade, s.supervisor_id , t.id as tea_id, t.`name` as tea_name, t.gender as tea_gender, t.research_area as tea_research_area, t.title as tea_title FROM student s LEFT JOIN teacher t ON s.supervisor_id = t.id
==> Parameters:
ooo Using Connection [[email protected]]
==>  Preparing: insert into student (id, name, gender, major, grade ) values (null,?,?,?,?) , ..., (null,?,?,?,?)
==> Parameters: 小哈哈00-0(String), ..., 100999999-999(String)
耗费时间:257 ms

对比2中保存的方式,那么可以查看到保存的时间上的差别

方法1:first quest costs:3267 ms

方法2:耗费时间:257 ms

结论在使用批量保存的时候使用方法2进行保存的效率会有较大的提升

时间: 2024-08-30 17:30:15

mybatis批量保存的相关文章

mybatis使用foreach进行批量保存

mysql下批量保存 mysql支持语法 inset into table values(),(),().... 可以使用foreach进行遍历保存第一种方法<insert id="addEmps" parameterType="queryVo" resultType="user"> insert into employee (last_name,email,gender) values <!-- foreach标签,进行遍历

MyBatis批量插入数据(MySql)

由于项目需要生成多条数据,并保存到数据库当中,在程序中封装了一个List集合对象,然后需要把该集合中的实体插入到数据库中,项目使用了Spring+MyBatis,所以打算使用MyBatis批量插入,应该要比循环插入的效果更好,由于之前没用过批量插入,在网上找了一些资料后最终实现了,把详细过程贴出来.供以后查阅和学习. java代码: 注意:这里循环的时候需new 出来新的对象,而不能通过循环改变属性的值就认为这是一个新的对象了,通俗的说就是new ReddemCode()要放在for循环的里面.

Mybatis批量Insert及水平分表

首先是Mybatis批量insert 说一下核心部分,整个工程参考我的github,运行的main方法在org/xiongmaotailang/mybatis/batchinsert/DbUtil.java中,涉及到的脚本是sql.txt 需要的数据表示例,包括4个字段. CREATE TABLE `newspvuv` (   `id` int(10) unsigned NOT NULL AUTO_INCREMENT,   `pv` bigint(11) DEFAULT NULL,   `uv`

mybatis批量删除,亲测可用

以前看了理论以为很容易就可以实现批量删除,谁知道自己写了才发现错误百出!百度mybatis批量删除,列出来的我没一个跑的通的(不排除是我自己的原因) 下面这种写法我自己测试是通过的! mybatis配置什么的这里不多提了,不懂也不会看到这个知识点 首先是mapper: <delete id="delStu" parameterType="java.util.List"> DELETE FROM STUDENT WHERE stuId IN <for

Mybatis批量更新数据

Mybatis批量更新数据 第一种方式 [html] view plain copy print? <update id="updateBatch" parameterType="Map"> update aa   set a=#{fptm}, b=#{csoftrain} where c in <foreach collection="cs" index="index" item="item&qu

myBatis批量添加,修改和删除

摘自: http://blog.csdn.net/myjlvzlp/article/details/8434376 1.批量添加元素session.insert(String string,Object o) public void batchInsertStudent(){ List<Student> ls = new ArrayList<Student>(); for(int i = 5;i < 8;i++){ Student student = new Student(

mybatis批量插入、批量删除

mybatis 批量插入 int addBatch(@Param("list")List<CustInfo> list); <insert id="addBatch" parameterType="java.util.List"> INSERT INTO CUSTINFO( SERIALID, CUSTID, INVNM, UPDATETIMESTAMP ) <foreach collection="lis

Mybatis批量删除之Error code 1064, SQL state 42000;

(一)小小的一次记载. (二):最近的项目都是使用MyBatis,批量新增自己都会写了,但是一次批量删除可把我给折腾了下,写法网上都有,但是照着做就是不行,最后问公司的人,问网友才得到答案,那就是jdbc中需要在url中指定允许进行进行多条语句同时执行. 自己在写批量更新的时候也把相应的语句打印出来了的,复制出来执行是没问题,但是用junit测试的时候一直报错如下 Error code 1064, SQL state 42000: You have an error in your SQL sy

解决Oracle+Mybatis批量插入报错:SQL 命令未正确结束

Mybatis批量插入需要foreach元素.foreach元素有以下主要属性: (1)item:集合中每一个元素进行迭代时的别名. (2)index:指定一个名字,用于表示在迭代过程中,每次迭代到的位置. (3)collection:根据传入的参数值确定. (4)open:表示该语句以什么开始. (5)separator:表示在每次进行迭代之间以什么符号作为分隔 符. (6)close:表示以什么结束. 首先,错误的xml配置文件如下: <insert id="save" da