67,512
社区成员
发帖
与我相关
我的任务
分享
public final Session currentSession() throws HibernateException {
//从线程局部量context中尝试取出已经绑定到线程的Session
Session current = existingSession( factory );
//如果没有绑定到线程的Session
if (current == null) {
//打开一个”事务提交后自动关闭”的Session
current = buildOrObtainSession();
current.getTransaction().registerSynchronization(buildCleanupSynch() );
// wrap the session in thetransaction-protection proxy
if ( needsWrapping( current ) ) {
current = wrap( current );
}
//将得到的Session绑定到线程中:即以<SessionFactory,Session>键值对方式设置到线程局部量context
doBind( current, factory );
}
return current;
}
我觉得是这样,只有当前session为null时才会去创建“事务提交后自动关闭”的Session,而使用了OpenSessionInViewFilter的session在当前请求范围内不会为nullpackage com.zjlolife.dao.impl;
import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.zjlolife.dao.UserDao;
import com.zjlolife.domain.User;
public class UserDaoBean implements UserDao{
@Resource
private SessionFactory sessionFactory;
public HibernateTemplate getHibernateTemplate() {
return new HibernateTemplate(sessionFactory);
}
public User load() {
/*Session session = sessionFactory.getCurrentSession();
return (User)session.load(User.class, 1);*/
return getHibernateTemplate().load(User.class, 1);
}
}
可是spring是怎么处理的呢?getCurrentSession会在事务提交的时候将session关闭的!spring是怎么处理的呢?上面两种方式 经测试都没有问题。。不知道为什么,希望大神来看看吧