https://www.cnblogs.com/juniorMa/p/13933192.html
在上一篇中,讲到一个非常重要的知识点,那就是每一个mapper对象的代理类执行方法的时候,都是每次都会new 一个SqlSession出来
但是我当时还有两个疑问
1 在SqlSessionInterceptor中我没有发现执行close的地方
2 为什么每次获取sqlsession的时候,判断ThreadLocal里面的缓存都是null呢?
经过不懈的努力,终于找到了原因,那就是由于使用了Spring提供的事务,这些资源的释放都是事务做的
代码在
SqlSessionUtils的内部类 SqlSessionSynchronization 的方法 @Override public void beforeCompletion() { // Issue #18 Close SqlSession and deregister it now // because afterCompletion may be called from a different thread if (!this.holder.isOpen()) { if (logger.isDebugEnabled()) { logger.debug("Transaction synchronization deregistering SqlSession [" + this.holder.getSqlSession() + "]"); } TransactionSynchronizationManager.unbindResource(sessionFactory); this.holderActive = false; if (logger.isDebugEnabled()) { logger.debug("Transaction synchronization closing SqlSession [" + this.holder.getSqlSession() + "]"); } this.holder.getSqlSession().close(); } }
AbstractPlatformTransactionManager
private void processCommit(DefaultTransactionStatus status) throws TransactionException { try { boolean beforeCompletionInvoked = false; try { prepareForCommit(status); triggerBeforeCommit(status); triggerBeforeCompletion(status); beforeCompletionInvoked = true; boolean globalRollbackOnly = false;
protected final void triggerBeforeCompletion(DefaultTransactionStatus status) { if (status.isNewSynchronization()) { if (status.isDebug()) { logger.trace("Triggering beforeCompletion synchronization"); } TransactionSynchronizationUtils.triggerBeforeCompletion(); } }
public static void triggerBeforeCompletion() { for (TransactionSynchronization synchronization : TransactionSynchronizationManager.getSynchronizations()) { try { synchronization.beforeCompletion(); } catch (Throwable tsex) { logger.error("TransactionSynchronization.beforeCompletion threw exception", tsex); } } }
其实怎么做原因也很明显,只有每次都new,每次都释放,才能保证多线程不报错