2014-09-22 233 views
2

我试图学习Hibernate和wicket。我实际上不确定何时打开和关闭休眠会话。我搜查了很多,阅读了许多关于会议工厂的事情,但我仍然没有得到它。休眠会话处理

我想获取我的数据库的一些数据,并将其显示在浏览器的表格中。这实际上工作,如果即时通讯第一次在该网站上,但如果我使用后退按钮,去到那个网站它再次表明我这个错误:

Last cause: Unknown service requested [org.hibernate.engine.jdbc.connections.spi.ConnectionProvider] 

我认为它是因为我闭上SessionFactory的早期或某事像那样。但我不知道如何解决这个问题。

我的Java类:

public class CategoryPanel extends Panel { 
    private WebMarkupContainer categoryContainer; 
    public CategoryPanel(String id) { 
     super(id); 
     SessionFactory sessionFactory = DbFactory.getSessionFactory();     // creating the Session Factory  
     StandardDao<Category> categoryDao = StandardDao.getInstance(sessionFactory); // creating dao to access data 
     List<Category> categoryList = categoryDao.getAll(Category.class);    // get data of the db 
     CategoryDataProvider dataProvider = new CategoryDataProvider(categoryList);   
     categoryContainer = new WebMarkupContainer("categoryTable"); 

     final DataView dv = new DataView("categoryList", dataProvider) { 

      @Override 
      protected void populateItem(Item item) { 
       final Category category = (Category) item.getModelObject(); 
       final CompoundPropertyModel<Category> categoryModel = new  CompoundPropertyModel<Category>(category); 

       item.add(new Label("catTitle", categoryModel.bind("title"))); 
      } 
     }; 
     categoryContainer.add(new Label("categoryTitle", Model.of("Titel"))); 
     add(categoryContainer); 
     sessionFactory.close(); // here I close the factory, this seems to be wrong. I dont know if i close it anyway.. 
    } 
} 

吾道:

public class StandardDao<T> { 
private static StandardDao instance = null; 
    private static final Object syncObject = new Object(); 
    private SessionFactory sessionFactory; 


    private StandardDao(SessionFactory session){ 
    this.sessionFactory = session; 
    } 

    public static StandardDao getInstance(SessionFactory session) { 
     if (instance == null) { 
      synchronized (syncObject) { 
       if (instance == null) { 
        instance = new StandardDao(session); 
       } 
      } 
     } 
     return instance; 
    } 
     public List<T> getAll(Class theClass) { 
      List<T> entity = null; 
      Session session = sessionFactory.openSession(); 
      try { 
       entity = session.createCriteria(theClass).list(); 
      } catch (RuntimeException e) { 
       e.printStackTrace(); 
      }finally { 
      session.flush(); 
      // if I close the session here, I cant load lazy 
     } 
      return entity; 
     } 
    } 

回答

4

你不应该关闭一个SessionFactory。 SessionFactory用于返回一个Session,在其上工作并关闭Session。

此外,您通常不会打开和关闭控制器代码中的会话,但将此处理委托给外部组件,每次请求到达时都可以从会话工厂打开新会话,并且最重要的是仅关闭它当请求完成时,也意味着视图部分完成了它的工作。

此模式通常称为“在视图中打开会话”。

在通常使用servlet过滤器完成的Java Web服务器中,您在web.xml中配置该服务器。

在Google视图筛选器中搜索Google for Java Open Session,您会发现很多示例和解释。