spring事物配置:
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
//org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
<property name="sessionFactory" ref="base_SessionFactory"/>
<property name="entityInterceptor" >
<bean id="daoInterceptor" class="com.test.DaoInterceptor"></bean>
</property>
</bean>
DaoInterceptor继承org.hibernate.EmptyInterceptor,可以在onSave、onFlushDirty、onLoad、afterTransactionCompletion自定义一些操作。
AnnotationSessionFactoryBean继承了父类AbstractSessionFactoryBean,父类实现了FactoryBean接口,因此HibernateTransactionManager注入的不是AnnotationSessionFactoryBean,而是SessionFactoryImpl
HibernateTransactionManager通过doGetTransaction、doBegin、doCommit等方法包装了hibernate的HibernateTransactionManager.HibernateTransactionObject和hibernate的session等类的方法。
- doGetTransaction返回的是HibernateTransactionManager.HibernateTransactionObject实体作为txObject
- doBegin为txObject配置Session并开启事务
//配置session
if (txObject.getSessionHolder() == null || txObject.getSessionHolder().isSynchronizedWithTransaction()) {
Interceptor entityInterceptor = this.getEntityInterceptor();
Session newSession = entityInterceptor != null ? this.getSessionFactory().openSession(entityInterceptor) : this.getSessionFactory().openSession();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Opened new Session [" + SessionFactoryUtils.toString(newSession) + "] for Hibernate transaction");
}
txObject.setSession(newSession);
}
session = txObject.getSessionHolder().getSession();
//开启事务
int timeout = this.determineTimeout(definition);
Transaction hibTx;
if (timeout != -1) {
hibTx = session.getTransaction();
hibTx.setTimeout(timeout);
hibTx.begin();
} else {
hibTx = session.beginTransaction();
}
txObject.getSessionHolder().setTransaction(hibTx);
- doRollback回滚事务