dra*_*aca 2 java hibernate servlets
我正在学习java servlet和hibernate.我有各自的工作示例,现在我正在尝试将hibernate示例合并到一个http servlet中.
我的简单hibernate示例以此代码开头
factory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = factory.openSession();
Run Code Online (Sandbox Code Playgroud)
当通过http get调用http servlet时,我理解它首先调用构造函数,然后调用doGet方法.
现在我的问题(因为我是新手,请对我很轻松):从servlet调用hibernate初始化代码的可接受方法是什么?我是否将上述初始化代码放在构造函数方法中?
有很多方法可以管理hibernate会话.最常见的方法之一是使用HibernateUtil类.通常的实现是,SessionFactory静态初始化,这意味着,初始化将只执行一次(当加载类时).然后它公开了一个静态方法来获取构建的SessionFactory实例.以下是dzone的实施示例.
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Run Code Online (Sandbox Code Playgroud)
对于会话的打开和关闭,它通常被视为具有请求处理的一个单元,因此您可以HibernateUtil.getSessionFactory().openSession()在方法的开头调用doGet或doPost确保在方法结束之前关闭会话.
| 归档时间: |
|
| 查看次数: |
7845 次 |
| 最近记录: |