Spring框架学习[Spring具体事务处理器的实现](十二)
on); //设置事务对象的事务隔离级别 txObject.setPreviousIsolationLevel(previousIsolationLevel); } //不允许为JDBC连接改成事务设置 else { //如果事务隔离级别不是默认事务隔离级别 if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) { throw new InvalidIsolationLevelException( "HibernateTransactionManager is not allowed to support custom isolation levels: " + "make sure that its 'prepareConnection' flag is on (the default) and that the " + "Hibernate connection release mode is set to 'on_close' (SpringTransactionFactory's default). " + "Make sure that your LocalSessionFactoryBean actually uses SpringTransactionFactory: Your " + "Hibernate properties should *not* include a 'hibernate.transaction.factory_class' property!"); } if (logger.isDebugEnabled()) { logger.debug( "Not preparing JDBC Connection of Hibernate Session [" + SessionFactoryUtils.toString(session) + "]"); } } //如果事务是只读,且事务对象是新的Hibernate Session if (definition.isReadOnly() && txObject.isNewSession()) { //设置Hibernate Session刷新模式为手动 session.setFlushMode(FlushMode.MANUAL); } //如果事务是非只读的,且事务对象不是新Hibernate Session if (!definition.isReadOnly() && !txObject.isNewSession()) { //或者Hibernate的刷新模式 FlushMode flushMode = session.getFlushMode(); //设置Session的刷新模式 if (flushMode.lessThan(FlushMode.COMMIT)) { session.setFlushMode(FlushMode.AUTO); //为事务对象设置刷新模式 txObject.getSessionHolder().setPreviousFlushMode(flushMode); } } Transaction hibTx; //获取事务超时时长 int timeout = determineTimeout(definition); //如果事务配置的超时时长不是事务默认超时时长 if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) { //获取Hibernate Session事务 hibTx = session.getTransaction(); //为事务对象设置超时时长 hibTx.setTimeout(timeout); //开启事务 hibTx.begin(); } //如果事务配置的超时时长是默认超时时长 else { //通过Hibernate Session直接开启事务 hibTx = session.beginTransaction(); } //把事务设置到事务对象的SessionHolder中,并且线程绑定 txObject.getSessionHolder().setTransaction(hibTx); //如果数据源不为null,即设置了数据源 if (getDataSource() != null) { //使用Hibernate Session打开
数据库连接 Connection con = session.connection(); //创建ConnectionHolder ConnectionHolder conHolder = new ConnectionHolder(con); //设置超时时长 if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) { conHolder.setTimeoutInSeconds(timeout); } if (logger.isDebugEnabled()) { logger.debug("Exposing Hibernate transaction as JDBC transaction [" + con + "]"); } //将数据源和JDBC ConnectionHolder绑定到当前线程 TransactionSynchronizationManager.bindResource(getDataSource(), conHolder); //将创建的JDBC ConnectionHolder设置到事务对象中 txObject.setConnectionHolder(conHolder); } //如果事务对象中的SessionHolder是新的 if (txObject.isNewSessionHolder()) { //当SessionHolder和当前线程绑定起来 TransactionSynchronizationManager.bindResource(getSessionFactory(), txObject.getSessionHolder()); } //设置事务对象中的SessionHolder是事务同步的 txObject.getSessionHolder().setSynchronizedWithTransaction(true); } //事务开启过程中异常处理 catch (Exception ex) { if (txObject.isNewSession()) { try { //如果Session的事务上激活的,回滚Session的事务 if (session.getTransaction().isActive()) { session.getTransaction().rollback();