双休整合下
整合struts2+spring3.2.1+hibernate4.2.1
结果遇到问题如下问题:
java.lang.NoSuchMethodError: org.hibernate.SessionFactory.openSession()Lorg/hibernate/classic/Session; at org.springframework.orm.hibernate3.SessionFactoryUtils.doGetSession(SessionFactoryUtils.java:323) at org.springframework.orm.hibernate3.SessionFactoryUtils.getSession(SessionFactoryUtils.java:235) at org.springframework.orm.hibernate3.HibernateTemplate.getSession(HibernateTemplate.java:457) at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:392) at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374) at org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:683)
检查配置文件,没有哪个地方用的hibernate3呀。
开始怀疑spring3,我用的是spring3提供的hibernateTemplate,怀疑hibernateTemplate用到的是hibernate3的方法。网上搜索,果然。
下面是他人的分析:“找不到方法,而我肯定导入了hibernate的jar包了,在网上搜索相关的文章,有人说这是在整合ssh时常出现的错误,主要指版本间的不兼容,我想这两个框架我都使用的是最新版本啊,怎么会不兼容呢。然后去spring的jar包里面看了一下才知道系统默认的使用的是.hibernate3.SessionFactoryUtils.doGetSession,而我使用的是hibernate4,那么原因肯定就在这里了,但是为什么在相同路径下就有.hibernate4.SessionFactoryUtils.doGetSession这个为什么不调用呢?”
参考
文章给出了hibernate3与hibernate4的区别,没有给出具体的解决办法,我等下解决了再贴上来~
-------------------------------我是改进的分割线--------------------------------
原本在DAO中将sessionFactory注入给HibernateTemplate,现在直接将sessionFactory注入给SessionFactory。然后用sessionFactory执行CRUD操作。代码如下:
在DAO中获取sessionFactory
private SessionFactory sessionFactory;@Resource(name="sessionFactory")public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory;}
通过sessionFactory执行CRUD
Session session = sessionFactory.openSession();session.beginTransaction();session.save( new Event( "Our very first event!", new Date() ) );session.save( new Event( "A follow up event", new Date() ) );session.getTransaction().commit();session.close();这样的改进只是通过spring将sessionFactory注入到DAO中,没有用到spring对hibernate的封装。代码比hibernateTemplate麻烦多啦!我再继续找找如何更好的整合。