zoukankan      html  css  js  c++  java
  • 【Java】线程需要独立的Connection,那对已经配好session的Spring/Mabatis工程该怎么办?

    方法一:让线程从配置中取DataSource。

    方法二:从配置中取出SessionFactory,然后交给线程去创建session和Connection,举例如下:

    // Get Session Factory
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("root-context.xml");
    DefaultSqlSessionFactory sqlSessionFactory=(DefaultSqlSessionFactory)ctx.getBean("sqlSessionFactory");
    
    for (String table : myJobInfo.tableList) {
    ... 
        CleanExpiredDataJobThread ct=new CleanExpiredDataJobThread();
        ct.setParams(index,table,myJobInfo.expiredDate,myJobInfo.commitSize,sqlSessionFactory,this);
        new Thread(ct).start();
    ...
    }

    线程里可以这样用:

    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
    
    public class CleanExpiredDataJobThread extends AbstractJob implements Job,Runnable {
        private org.apache.ibatis.session.defaults.DefaultSqlSessionFactory sqlSessionFactory;
        
        ....
    
    
        @Override
        public void run(){
            logger.info("Start...");
            long startTime = System.currentTimeMillis();
            
            try {
                SqlSession sqlSession = null;
                sqlSession = sqlSessionFactory.openSession();
                
                // get connection and set it's auto-commit status to false
                Connection conn = getConnection(sqlSession);
                
                ....
            }catch(Exception ex) {
                ex.printStackTrace();
            }finally {
                
            }
            
        }
    }

    --END-- 2019年11月17日12:08:15

  • 相关阅读:
    2.7 矩阵的秩
    HDU
    HDU
    HDU
    HDU
    HDU
    hdu 5179 beautiful number(数位dp)
    ACdream
    CodeForces
    <a>标签中 href="/" 和 hideFocus="true"
  • 原文地址:https://www.cnblogs.com/heyang78/p/11875909.html
Copyright © 2011-2022 走看看