hibernateutil.java

来自「MM7彩信对接网关示例」· Java 代码 · 共 53 行

JAVA
53
字号
package com.rainbow.util.tools;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static Logger log = Logger.getLogger(HibernateUtil.class);

    private static final SessionFactory sessionFactory;

    static {
        try {
        	System.out.println("Read HibernateUtil Config");

            // Create the SessionFactory
        	//File file = new File("conf/hibernate.cfg.xml");
        	Configuration cfg = new Configuration();
        	cfg.configure(UtilURL.fromResource("conf/hibernate.cfg.xml"));
        	//System.out.println("Read HibernateUtil Config Success11");
        	sessionFactory = cfg.buildSessionFactory();
        	//System.out.println("Read HibernateUtil Config Success22");
            //sessionFactory = new Configuration().configure().buildSessionFactory();
        	
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            log.error("Initial SessionFactory creation failed.", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static final ThreadLocal session = new ThreadLocal();

    public static Session currentSession()  {
        Session s = (Session) session.get();
        // Open a new Session, if this Thread has none yet
        if (s == null) {
            s = sessionFactory.openSession();
            session.set(s);
        }
        return s;
    }

    public static void closeSession() {
        Session s = (Session) session.get();
        if (s != null)
            s.close();
        session.set(null);
    }
}

⌨️ 快捷键说明

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