我的项目是S2SH 三个框架整合的,但是我需要写一个工具类,需要获取SessionFactory,但是我无论我继承dao或者service,都是空指针,我用过 WebApplicationContextWare 来获取bean,即获取spring管理的其中的sessionFactory bean,但是还是空指针,请问各位路过的高手,如何在脱离Spring的情况下 ,成功获取SessionFactory,从而获取到Session呢?急..........

解决方案 »

  1.   

    如何在脱离Spring的情况下 ,成功获取SessionFactory,如下:Configuration config=new Configuration().configure();
    SessionFactory factory=config.buildSessionFactory();
      

  2.   

    Configuration config=new Configuration().configure();
    SessionFactory factory=config.buildSessionFactory();2楼这样的方式 是存在hibernate.cfg.xml时才有用,当时我的项目是applicationContext.xml管理sessionfactory,没有用到hibernate.cfg.xml这个文件配置,这种情况下,需要成功获取sessionfactory有没有其他方式呢?
      

  3.   

    是不是放到hibernateTemplate里面去了?我一般是用hibernateTemplate
      

  4.   

    在applicationContext.xml里而设置注入,把sessionFatory注入到你的工具类里,然后在那所用的工具用继承HibernateDaoSupport,用hibernateTemplate来获取sessionFactory。可以不?
      

  5.   

    我靠。你在开玩笑吗。由容器管理的东西。你要在脱离容器之后获得它?
    如果你的dao继承了hibernatedaosupport,那么可以通过dao.getSessionFactory获取。
    如果你没有使用hibernatetemplate或者hibernatedaosupport,你可以通过WebApplicationContextUtils
    .getWebApplicationContext(ServletActionContext.getServletContext()).getBean()获得
    其实还有办法。
      

  6.   


    如何成功获取SessionFactory,从而获取到Session呢?急..........
    顶!!
      

  7.   

    如果你的dao继承了hibernatedaosupport,那么可以通过dao.getSessionFactory获取。
    如果你没有使用hibernatetemplate或者hibernatedaosupport,你可以通过WebApplicationContextUtils
    .getWebApplicationContex.getBean("");获得
      

  8.   

    sessionFactory.getCurrentSession()..................前提是spring管理的事物这个东西才能用。不然是为空的,你可能就要用sessionFactory.openSession()了。
    你这临阵磨枪,一点不光啊
      

  9.   

    我觉得你的公具类只要继承HibernateDaoSupport这个类就行了,应该就可以连接数据库了啊这样工具类跟dao里面的应该是一样用的。。
      

  10.   


          5楼正解!sessionFactory 已经交给spring 容器去托管了,实例化的过程是我们控制不了的,只能通过注入,检查一下你的配置文件,如果是没有注入,将sessionFactory 注入到你的工具类中应该就OK了。还有问题的话发上来...
      

  11.   

    ApplicationContext ac = new FileSystemXmlApplicationContext(
      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();
      

  12.   

    我写的工具类没有继承HibernateDaoSupport的,也没有在applicationContext.xml里面注入,用WebApplicationContextUtils.getWebApplicationContex.getBean("");获得的是空指针,各位可以写清楚仔细的注入和获取的代码吗
      

  13.   

    你的配置文件必然存在这样一个定义,尽量领会思想。
    <bean id="hibernateTemplate" class="....HibernateTemplate"/>
    你可以在代码中这样写
    WebApplicationContextUtils.getWebApplicationContex.getBean("hibernateTemplate").getSessionFactory().getCurrentSession();
    但是这样写是有前提的。
    第一必须是在web环境。
    第二必须是spring管理事务。
    第三你的测试代码必须包含一个完整的事务。其实你的需求大可不必这样写,只需要在你的dao里面注入template就可以调用后面的方法了。