而execute方法,看源码HibernateTemplate中写道
1
2
3
4
5
6
|
public Object execute(HibernateCallback action, boolean exposeNativeSession) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null" );
Session session = getSession();
boolean existingTransaction = (!isAlwaysUseNewSession() &&
(!isAllowCreate() || SessionFactoryUtils.isSessionTransactional(session, getSessionFactory())));
|
其中getSession,代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
protected Session getSession() {
if (isAlwaysUseNewSession()) {
return SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor());
}
else if (isAllowCreate()) {
return SessionFactoryUtils.getSession(
getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
}
else {
try {
return getSessionFactory().getCurrentSession();
}
catch (HibernateException ex) {
throw new DataAccessResourceFailureException( "Could not obtain current Hibernate Session" , ex);
}
}
}
|
注意这里:else if (isAllowCreate()),其中在HibernateTemplate类中默认private boolean allowCreate = true;
意思说如果当前线程中的session不存在的话,是否允许创建,而默认是允许的,通过函数名字就很清楚,接下来是创建当前线程中的session的代码。
http://bbs.csdn.net/topics/280063179
1: @Transactional声明的方法执行时,Spring的TransactionManager会自动Open Sesion,自动开启事务,并且将此Sesion绑定到SpringSessionContext(实际上是TransactionSynchronizationManager的ThreadLocal的Map)中..
2:SessionFactory.getCurrentSession()方法执行时,调用SpringSessionContext.currentSession()从TransactionSynchronizationManager的上下文中查找 当前的Session
3:找到后返回当前的Session,找不到,则返回HibernateException("No Sessionfound for current thread")
PS: 从中,我们也知道了,执行SessionFactoryImpl.openSession()时,只是简单地new 一个SessionBuilder,然后调用SessionBuilder.openSession(),得到的Session是不会绑定到任何 org.hibernate.context.spi.CurrentSessionContext 在上下文中的.