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;
}
}