【发布时间】:2014-09-22 08:20:29
【问题描述】:
我正在尝试学习休眠和检票口。我实际上不确定何时打开和关闭休眠会话。我已经搜索了很多并阅读了很多关于会话工厂的内容,但我仍然不明白。
我想从我的数据库中获取一些数据并将其显示在浏览器的表格中。如果我是第一次访问该网站,这实际上是可行的,但是如果我使用后退按钮并再次访问该网站,它会向我显示此错误:
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;
}
}
【问题讨论】:
标签: java hibernate session wicket