使用工具类管理SessionFactory和Session

使用工具类管理SessionFactory和Session

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
private static Configuration configuration;
private final static SessionFactory sessionFactory;

//初始化Configuration和SessionFactory
static {
try {
//配置文件名,来源resources 根目录
configuration = new Configuration().configure("hibernate.cfg.xml");
sessionFactory = configuration.buildSessionFactory();
} catch (HibernateException e) {
throw new ExceptionInInitializerError(e);
}
}

//获取Session对象
public static Session currentSesstion() {
return sessionFactory.getCurrentSession();
}
}