package com.utils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
/**
* Created by Jiro.Chen on 2017/11/7.
*/
public class HibernateUtils {
private static SessionFactory sessionFactory = null;
static {
try {
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}catch (HibernateException e){
System.out.println("SessionFactory初始化失败");
e.printStackTrace();
}
}
public static SessionFactory getSessionFactory() throws Exception{
if (sessionFactory != null){
return sessionFactory;
}else {
throw new Exception("sessionFactory为空,请检查配置文件");
}
}
public static Session getSession(){
Session session = null;
try {
if (sessionFactory != null){
session = sessionFactory.openSession();
}
}catch (HibernateException e){
e.printStackTrace();
}
return session;
}
public static void closeSession(Session session){
try {
if (session != null && session.isOpen()){
session.close();
}
}catch (HibernateException e){
e.printStackTrace();
}
}
}
Hibernate4学习记录三(HibernateUtils工具类设计)
最新推荐文章于 2020-12-12 12:52:47 发布