我正在学习java servlet和hibernate。我有各自的工作示例,现在我正在尝试将hibernate示例合并到一个http servlet中。
我的简单hibernate示例以此代码
开头factory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = factory.openSession();
当通过http get调用http servlet时,我理解它首先调用构造函数,然后调用doGet方法。
现在我的问题(因为我是新手,请对我这么容易):从servlet调用hibernate初始化代码的可接受方法是什么?我是否将上述初始化代码放在构造函数方法中?
答案 0 :(得分:7)
有很多方法可以管理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;
}
}
对于会话的开启和结束,通常会将其视为一个包含请求处理的单元,因此您可以在HibernateUtil.getSessionFactory().openSession()
或doGet
的开头调用doPost
并确保关闭方法结束前的会话。
答案 1 :(得分:3)
为Hibernate Connection创建一个单独的类。
package com.abc.xyz.dao;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
@SuppressWarnings("deprecation")
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from Annotation
return new AnnotationConfiguration().configure().buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
在服务器端获取该
的连接 Session session=null;
try {
session =HibernateUtil.getSessionFactory().openSession();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
session.close();
}
答案 2 :(得分:-4)
尝试使用servlet监听器。