日期:2014-05-20  浏览次数:20804 次

hibernate +spring



public static void main(String[] args) {
  ApplicationContext contest=new ClassPathXmlApplicationContext("applicationContext.xml");
  ManagerDao dao=(ManagerDao)contest.getBean("Manager");

  System.out.println(dao.getSessionFactory().getCurrentSession())
   
}

这是的测试的方法
要是只输出:dao.getSessionFactory()就没错 
 当输出:dao.getSessionFactory().getCurrentSession();
  就报下面这个错

Exception in thread "main" org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)

at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:508)
at Test.Test.main(Test.java:19)

------解决方案--------------------
是不是在这个main方法里面,session没有办法绑定这个thread呀。
你用单元测试试试
------解决方案--------------------
报错的原因是楼主在调用dao.getSessionFactory().getCurrentSession()方法之前没有将session绑定到当前线程中造成的,你可以在Manager的实现类里这样写session = HibernateUtils.getSessionFactory().getCurrentSession();这样就可以把session绑定到当前线程了,openSession()和getCurrentSession()的区别是openSession()不会绑定线程并且要手动关闭session.使用getCurrentSession()需要在hibernate.cfg.xml文件中加入如下配置:
如果使用的是本地事务(jdbc事务)
<property name="hibernate.current_session_context_class">thread</property>
如果使用的是全局事务(jta事务)
<property name="hibernate.current_session_context_class">jta</property>


------解决方案--------------------
我的blog对这个解释的比较清楚

http://blog.csdn.net/Landor2004/archive/2008/12/18/3546267.aspx