目录
一、问题描述
在Hibernate中需要使用Session对象来完成数据的操作,那么该如何获取Session对象?我们可以通过SessionFactory来获取Session对象,我们可以将SessionFactory写成单例模式,避免创建多个SessionFactory,导致数据库性能降低
在工程代码中使用SessionFactory的openSession方法获取session对象
二、工程代码
package com.codecoord.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/** 采用单例模式 */
public class HibernateUtil {
// SessionFactory工厂 用于获取Session
private static SessionFactory factory;
// 构造方法私有化
private HibernateUtil() {}
// 初始化SessionFactory
private static void init() {
// 不为空则创建SessionFactory
if (factory == null) {
Configuration config = new Configuration(); // 配置对象
config.configure("hibername.cfg.xml"); // 加载配置文件
factory = config.buildSessionFactory(); // 构造工厂对象
}
}
/** 获取连接 */
public static Session getSession() {
if (factory == null) {
init();
}
return factory.openSession();
}
}