方法一:让线程从配置中取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