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()方法,让其直接冲刷到数据库进行执行。

  • 相关阅读:
    JDBC在getConnection之前为什么要调用Class.forName(转)
    ThreadPoolExecutor的一点理解 专题
    java.lang.NoSuchMethodError
    POJ 3380 最大流
    Spring3.0 AOP 具体解释
    深入浅出 RPC
    JUnit入门
    Linux makefile 教程 很具体,且易懂
    怎样修复“Windows/System32/Config/System中文件丢失或损坏”故障
    MessageDigest简单介绍
  • 原文地址:https://www.cnblogs.com/SkyeAngel/p/8492102.html
Copyright © 2011-2022 走看看