public class HibernateUtil {
//session工厂
public static SessionFactory sessionFactory=null;
//session 绑定到本地线程
public static ThreadLocal<Session> sessionLocal= new ThreadLocal<Session>();
public static Session getSession(){
Session session= sessionLocal.get();
if (session==null) {
if (sessionFactory==null) {
//构建配置对象 这里是使用了注解 用的 AnnotationConfiguration 不使用注解用Configuration就好
Configuration configuration=new AnnotationConfiguration();
//Hibernate初始化
configuration.configure();
//构建sessionfactory
sessionFactory= configuration.buildSessionFactory();
}
//创建新的 session
session= sessionFactory.openSession();
//放入本地线程
sessionLocal.set(session);
}
return session;
}
public static void beginTransaction(){
//获取当前线程的session
Session session= getSession();
if (session!=null) {
//开启事物
session.beginTransaction();
}
}
public static void commitTransaction(){
//获取当前线程的session
Session session= getSession();
if (session!=null) {
//开启事物
Transaction transaction= session.beginTransaction();
//不为空,没有提叫,没有回滚
if (transaction!=null&&!transaction.wasRolledBack()&&!transaction.wasCommitted()) {
transaction.commit();
}
}
}
public static void rollerBackTransaction(){
//获取当前线程的session
Session session= getSession();
if (session!=null) {
//开启事物
Transaction transaction= session.beginTransaction();
//不为空,没有提叫,没有回滚
if (transaction!=null&&!transaction.wasRolledBack()&&!transaction.wasCommitted()) {
transaction.rollback();
}
}
}
public static void closeSession(){
//获取当前线程的session
Session session= getSession();
if (session!=null) {
//解除本地绑定
sessionLocal.remove();
//如果不是打开就关闭
if (session.isOpen()) {
session.close();
}
}
}
}