我的项目是S2SH 三个框架整合的,但是我需要写一个工具类,需要获取SessionFactory,但是我无论我继承dao或者service,都是空指针,我用过 WebApplicationContextWare 来获取bean,即获取spring管理的其中的sessionFactory bean,但是还是空指针,请问各位路过的高手,如何在脱离Spring的情况下 ,成功获取SessionFactory,从而获取到Session呢?急..........
调试欢乐多
SessionFactory factory=config.buildSessionFactory();
SessionFactory factory=config.buildSessionFactory();2楼这样的方式 是存在hibernate.cfg.xml时才有用,当时我的项目是applicationContext.xml管理sessionfactory,没有用到hibernate.cfg.xml这个文件配置,这种情况下,需要成功获取sessionfactory有没有其他方式呢?
如果你的dao继承了hibernatedaosupport,那么可以通过dao.getSessionFactory获取。
如果你没有使用hibernatetemplate或者hibernatedaosupport,你可以通过WebApplicationContextUtils
.getWebApplicationContext(ServletActionContext.getServletContext()).getBean()获得
其实还有办法。
如何成功获取SessionFactory,从而获取到Session呢?急..........
顶!!
如果你没有使用hibernatetemplate或者hibernatedaosupport,你可以通过WebApplicationContextUtils
.getWebApplicationContex.getBean("");获得
你这临阵磨枪,一点不光啊
5楼正解!sessionFactory 已经交给spring 容器去托管了,实例化的过程是我们控制不了的,只能通过注入,检查一下你的配置文件,如果是没有注入,将sessionFactory 注入到你的工具类中应该就OK了。还有问题的话发上来...
new String[] { "applicationContext.xml的物理路径" });
SessionFactory sf = (SessionFactory) ac.getBean("sf");
/*sf:注入的<bean id="sfid"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dsid" />...
*/
sf.method();
<bean id="hibernateTemplate" class="....HibernateTemplate"/>
你可以在代码中这样写
WebApplicationContextUtils.getWebApplicationContex.getBean("hibernateTemplate").getSessionFactory().getCurrentSession();
但是这样写是有前提的。
第一必须是在web环境。
第二必须是spring管理事务。
第三你的测试代码必须包含一个完整的事务。其实你的需求大可不必这样写,只需要在你的dao里面注入template就可以调用后面的方法了。