这段代码是hibernate5.02版本写的。
package com.mxf.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
/**
* 采用饿汉模式设计该类
*
*/
public class HibernateUtils {
private HibernateUtils() {
}
private static HibernateUtils instance = new HibernateUtils();
public static HibernateUtils getInstance() {
return instance;
}
private SessionFactory sessionFactory;
private StandardServiceRegistry standardServiceRegistry;
private Transaction tx;
private Session session;
public SessionFactory getSessionFactory() {
if (sessionFactory == null) {
standardServiceRegistry = new StandardServiceRegistryBuilder().configure().build();
sessionFactory = new MetadataSources(standardServiceRegistry).buildMetadata().buildSessionFactory();
}
return sessionFactory;
}
/**
* 得到线程安全的session
* @return
*/
public Session getSession() {
session = getSessionFactory().getCurrentSession();
return session;
}
public Transaction getTx() {
tx = getSession().beginTransaction();
return tx;
}
public void commitTx() {
tx.commit();
session.close();
}
}