这个实例里主要存放的就 是sessionholder,sessionholder里存放的就是开始事务的session和transaction对象, 如果之前没有sessionholder存放到线程中,那么这个HibernateTransactionObject的实 例的属性其实是空的,这一点可以在doBegin方法的实现中看出来
protected void doBegin(Object transaction, TransactionDefinition definition) {
if (getDataSource() != null && TransactionSynchronizationManager.hasResource(getDataSource())) {
throw new IllegalTransactionStateException(
"Pre-bound JDBC Connection found - HibernateTransactionManager does not support " +
"running within DataSourceTransactionManager if told to manage the DataSource itself. " +
"It is recommended to use a single HibernateTransactionManager for all transactions " +
"on a single DataSource, no matter whether Hibernate or JDBC access.");
}
Session session = null;
try {
HibernateTransactionObject txObject = (HibernateTransactionObject) transaction;
if (txObject.getSessionHolder() == null) {
Interceptor entityInterceptor = getEntityInterceptor();
Session newSession = (entityInterceptor != null ?
getSessionFactory().openSession(entityInterceptor) : getSessionFactory ().openSession());
if (logger.isDebugEnabled()) {
logger.debug("Opened new Session [" + newSession + "] for Hibernate transaction");
}
txObject.setSessionHolder(new SessionHolder(newSession), true);
}//我们看到,如果传进来的transaction中并没有存放sessionholder,那么就新建一 个session,放到新的sessionholder中,再放到HibernateTransactionObject的实例中去 ,顺便说一下,这个变量的名字取得真是差,虽然是Juergen Hoeller写的,也要批一下, 搞得别人会以为是Transaction的实例
txObject.getSessionHolder().setSynchronizedWithTransaction(true);
session = txObject.getSessionHolder().getSession();
Connection con = session.connection();
Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
txObject.setPreviousIsolationLevel(previousIsolationLevel);
if (definition.isReadOnly() && txObject.isNewSessionHolder()) {
// Just set to NEVER in case of a new Session for this transaction.
session.setFlushMode(FlushMode.NEVER);
}//如果是只读事务,并且sessionholder是新建的,那么就设置hibernate的flushmode 为never
if (!definition.isReadOnly() && ! txObject.isNewSessionHolder()) {
// We need AUTO or COMMIT for a non-read-only transaction.
FlushMode flushMode = session.getFlushMode();
if (FlushMode.NEVER.equals(flushMode)) {
session.setFlushMode(FlushMode.AUTO);
//如果session的flushmode是nerver,就设置为auto,因为如果事务定义成非readonly ,那么这个session一定是可以flush的
txObject.getSessionHolder().setPreviousFlushMode(flushMode);
}
}
// Add the Hibernate transaction to the session holder.
txObject.getSessionHolder().setTransaction(session.beginTransaction());//开 始一个事务,并把这个事务对象放到sessionholder中,随后这个sessionholder会通过 threadlocal放到线程中,以供在commit时使用
// Register transaction timeout.
if (definition.getTimeout() != Transact
|