hibernate4 + spring3 整合報錯問題


錯誤:java.lang.NoSuchMethodError: org.hibernate.SessionFactory.openSession()Lorg/hibernate/classic/Session;

原因:Hibernate4和Hibernate3不一樣的地方 
1.不能在使用HibernateTemplate,Spring已經不建議使用了,應該將SessionFactory直接注入到DAO,而不再是HibernateTemplate

2.不能使用openSession,openSession獲取的session是不受Spring切面事務管理的,必須使用 getCurrentSession ,而且必須開啓事務, getCurrentSession 才能正確獲取到,因爲在Spring3中session是被綁定在SpringSessionContext中的,所以 getCurrentSession 是從這個上下文的線程局部變量去獲取session,而且只有開啓事務了,session纔會綁定到這個上下文中

修改相應的配置文件:
applicationContext.xml
<context:annotation-config />
<!-- session Factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
     <property name="dataSource">
      <ref bean="dataSource"/>
     </property>
     <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
    </bean> 

<bean id="scDao" class="dao.SCDao">
     <property name="sessionFactory">
   <ref bean="sessionFactory" />
  </property>
    </bean>

Dao中注入:

@Resource(name="sessionFactory")
 private SessionFactory sessionFactory ;

public void saveStu(Stu stu){
  Session session = sessionFactory.openSession();
  session.save(stu);
  session.close();
 }

原先hibernate3的寫法:
public void delEntity(Object obj){
  try {
   getHibernateTemplate().delete(obj);
  } catch (DataAccessException e) {
   e.printStackTrace();
  }
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章