⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 hibernateutil.java

📁 sistem information for universitas
💻 JAVA
字号:
package dao;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
    private static final SessionFactory sessionFactory;
    private static final ThreadLocal threadSession=new ThreadLocal();
    private static final ThreadLocal threadTransaction=new ThreadLocal();
    static
    {
        try {
            sessionFactory=new Configuration().configure().buildSessionFactory();
        } catch(Throwable ex) {
            System.err.println("Initial SessionFactory failed. "+ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static Session getSession() {
        Session s=(Session)threadSession.get();
        try {
            if(s==null) {
                s=sessionFactory.openSession();
                threadSession.set(s);
            }
        } catch(HibernateException ex) {
            throw ex;
        }
        return s;
    }
    public static void closeSession() {
        try {
            Session s=(Session)threadSession.get();
            threadSession.set(null);
            if(s!=null && s.isOpen()) {
                s.close();
            }
        } catch(HibernateException ex) {
            throw ex;
        }
    }
    public static void beginTransaction() {
        Transaction tx=(Transaction) threadTransaction.get();
        try {
            if (tx == null) {
                tx=getSession().beginTransaction();
                threadTransaction.set(tx);
            }
        } catch (HibernateException ex) {
            throw ex;
        }
    }
    public static void commitTransaction() {
        Transaction tx=(Transaction) threadTransaction.get();
        try {
            if(tx!=null&&!tx.wasCommitted()&&!tx.wasRolledBack()) {
                tx.commit();
            }
            threadTransaction.set(null);
        } catch (HibernateException ex) {
            rollbackTransaction();
            throw ex;
        }
    }
    public static void rollbackTransaction() {
        Transaction tx=(Transaction)threadTransaction.get();
        try {
            threadTransaction.set(null);
            if(tx!=null&&!tx.wasCommitted()&&!tx.wasRolledBack()) {
                tx.rollback();
            }
        } catch(HibernateException ex) {
            throw ex;
        } finally {
            closeSession();
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -