zoukankan      html  css  js  c++  java
  • JavaEE——Mybatis(19)--MyBatis实用场景 2.批量操作

    测试时:只需要在创建SQLSession的openSession时,指定SqlSession openSession = sqlSessionFactory.openSession( ExecutorType.BATCH );

    @Test
    	public void testBatch() throws IOException {
    		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    
    		//可以执行批量操作的sqlSession
    		SqlSession openSession = sqlSessionFactory.openSession( ExecutorType.BATCH );
    		long start = System.currentTimeMillis();
    		try{
    			StudentMapper studentMapper = openSession.getMapper(StudentMapper.class);
    
    			for(int i = 0; i < 10000; ++i){
    				studentMapper.addStu( new Student( UUID.randomUUID().toString().substring( 0, 3 ), "girl", 18) );
    			}
    
    			openSession.commit();
    			long end = System.currentTimeMillis();
    			//批量:(预编译sql一次==》设置参数10000次==》执行1次)8070ms
    			//Parameters: 236(String), girl(String), 18(Integer)
    			//非批量:(预编译sql,设置参数,执行)==》10000次  18153ms
    			System.out.println("执行时长:" + (end - start));
    
    		}finally{
    			openSession.close();
    		}
    
    	}
    

      

    而与Spring整合时:在Spring的配置文件applicationContext.xml中配置

    使用时:

    在Service层

    注意:
      • 1、批量操作是在session.commit()以后才发送sql语句给数据库进行执行的
      • 2、如果我们想让其提前执行,以方便后续可能的查询操作获取数据,我们可以使用sqlSession.flushStatements()方法,让其直接冲刷到数据库进行执行。

  • 相关阅读:
    1434. Buses in Vasyuki 夜
    SAP
    目标
    组合数
    KM算法模板
    网络流
    CodeForces 43E
    B. Unsorting Array codeforces 127
    Colorful Rainbows 127
    C. Anagram codeforces
  • 原文地址:https://www.cnblogs.com/SkyeAngel/p/8492102.html
Copyright © 2011-2022 走看看