这个util类可以吗?
public class HbnUtil3 {
    private static SessionFactory sf;
 
    static {
        try {
            sf = new Configuration().configure().buildSessionFactory();
        } catch (HibernateException e) {
            e.printStackTrace();
        }
    }     public static Session getCurrentSession() {
        if (sf == null)
        return null;
        return sf.getCurrentSession();
    }     public static void clearSessionFactory() {
        if (sf != null && !sf.isClosed())
        sf.close();
    }}

解决方案 »

  1.   

    Hibernate不是有自己的util类吗?
      

  2.   

    这样的代码只能是自己测试的时候使用。写一个单例的就ok,不需要什么static{}这样处理
      

  3.   


    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.hibernate.HibernateException;
    import org.hibernate.Interceptor;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;/**
     * 
     * @author fei
     * 
     */
    public class HibernateUtil2 {
    private static Log log = LogFactory.getLog(HibernateUtil2.class); private static Configuration configuration;
    private static SessionFactory sessionFactory;
    private static final ThreadLocal threadSession = new ThreadLocal();
    private static final ThreadLocal threadTransaction = new ThreadLocal();
    private static final ThreadLocal threadInterceptor = new ThreadLocal(); // Create the initial SessionFactory from the default configuration files
    static {
    try {
    configuration = new Configuration();
    sessionFactory = configuration.configure().buildSessionFactory();
    // We could also let Hibernate bind it to JNDI:
    // configuration.configure().buildSessionFactory()
    } catch (Throwable ex) {
    // We have to catch Throwable, otherwise we will miss
    // NoClassDefFoundError and other subclasses of Error
    log.error("Building SessionFactory failed.", ex);
    throw new ExceptionInInitializerError(ex);
    }
    } /**
     * Returns the SessionFactory used for this static class.
     * 
     * @return SessionFactory
     */
    public static SessionFactory getSessionFactory() {
    // Instead of a static variable, use JNDI:
    // SessionFactory sessions = null;
    // try {
    // Context ctx = new InitialContext();
    // String jndiName = "java:hibernate/HibernateFactory";
    // sessions = (SessionFactory)ctx.lookup(jndiName);
    // } catch (NamingException ex) {
    // throw new InfrastructureException(ex);
    // }
    // return sessions; return sessionFactory;
    } /**
     * Returns the original Hibernate configuration.
     * 
     * @return Configuration
     */
    public static Configuration getConfiguration() {
    return configuration;
    } /**
     * Rebuild the SessionFactory with the static Configuration.
     * 
     */
    public static void rebuildSessionFactory()
    throws ExceptionInInitializerError {
    synchronized (sessionFactory) {
    try {
    sessionFactory = getConfiguration().buildSessionFactory();
    } catch (Exception ex) {
    throw new ExceptionInInitializerError(ex);
    }
    }
    } /**
     * Rebuild the SessionFactory with the given Hibernate Configuration.
     * 
     * @param cfg
     */
    public static void rebuildSessionFactory(Configuration cfg)
    throws ExceptionInInitializerError {
    synchronized (sessionFactory) {
    try {
    sessionFactory = cfg.buildSessionFactory();
    configuration = cfg;
    } catch (Exception ex) {
    throw new ExceptionInInitializerError(ex);
    }
    }
    } /**
     * Retrieves the current Session local to the thread.
     * <p/>
     * If no Session is open, opens a new Session for the running thread.
     * 
     * @return Session
     */
    public static Session getSession() throws ExceptionInInitializerError {
    Session s = (Session) threadSession.get();
    try {
    if (s == null) {
    log.debug("Opening new Session for this thread.");
    if (getInterceptor() != null) {
    log.debug("Using interceptor: "
    + getInterceptor().getClass());
    s = getSessionFactory().openSession(getInterceptor());
    } else {
    s = getSessionFactory().openSession();
    }
    threadSession.set(s);
    }
    } catch (HibernateException ex) {
    throw new ExceptionInInitializerError(ex);
    }
    return s;
    } /**
     * Closes the Session local to the thread.
     */
    public static void closeSession() throws ExceptionInInitializerError {
    try {
    Session s = (Session) threadSession.get();
    threadSession.set(null);
    if (s != null && s.isOpen()) {
    log.debug("Closing Session of this thread.");
    s.close();
    }
    } catch (HibernateException ex) {
    throw new ExceptionInInitializerError(ex);
    }
    } /**
     * Start a new database transaction.
     */
    public static void beginTransaction() throws ExceptionInInitializerError {
    Transaction tx = (Transaction) threadTransaction.get();
    try {
    if (tx == null) {
    log.debug("Starting new database transaction in this thread.");
    tx = getSession().beginTransaction();
    threadTransaction.set(tx);
    }
    } catch (HibernateException ex) {
    throw new ExceptionInInitializerError(ex);
    }
    } /**
     * Commit the database transaction.
     */
    public static void commitTransaction() throws ExceptionInInitializerError {
    Transaction tx = (Transaction) threadTransaction.get();
    try {
    if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
    log.debug("Committing database transaction of this thread.");
    tx.commit();
    }
    threadTransaction.set(null);
    } catch (HibernateException ex) {
    rollbackTransaction();
    throw new ExceptionInInitializerError(ex);
    }
    } /**
     * Commit the database transaction.
     */
    public static void rollbackTransaction() throws ExceptionInInitializerError {
    Transaction tx = (Transaction) threadTransaction.get();
    try {
    threadTransaction.set(null);
    if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
    log.debug("Tyring to rollback database transaction of this thread.");
    tx.rollback();
    }
    } catch (HibernateException ex) {
    throw new ExceptionInInitializerError(ex);
    } finally {
    closeSession();
    }
    } /**
     * Reconnects a Hibernate Session to the current Thread.
     * 
     * @param session
     *            The Hibernate Session to be reconnected.
     */
    public static void reconnect(Session session)
    throws ExceptionInInitializerError {
    try {
    session.reconnect();
    threadSession.set(session);
    } catch (HibernateException ex) {
    throw new ExceptionInInitializerError(ex);
    }
    } /**
     * Disconnect and return Session from current Thread.
     * 
     * @return Session the disconnected Session
     */
    public static Session disconnectSession()
    throws ExceptionInInitializerError { Session session = getSession();
    try {
    threadSession.set(null);
    if (session.isConnected() && session.isOpen())
    session.disconnect();
    } catch (HibernateException ex) {
    throw new ExceptionInInitializerError(ex);
    }
    return session;
    } /**
     * Register a Hibernate interceptor with the current thread.
     * <p>
     * Every Session opened is opened with this interceptor after registration.
     * Has no effect if the current Session of the thread is already open,
     * effective on next close()/getSession().
     */
    public static void registerInterceptor(Interceptor interceptor) {
    threadInterceptor.set(interceptor);
    } private static Interceptor getInterceptor() {
    Interceptor interceptor = (Interceptor) threadInterceptor.get();
    return interceptor;
    }}
      

  4.   

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.hibernate.HibernateException;
    import org.hibernate.Interceptor;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;/**
     * 
     * @author fei
     * 
     */
    public class HibernateUtil2 {
        private static Log log = LogFactory.getLog(HibernateUtil2.class);    private static Configuration configuration;
        private static SessionFactory sessionFactory;
        private static final ThreadLocal threadSession = new ThreadLocal();
        private static final ThreadLocal threadTransaction = new ThreadLocal();
        private static final ThreadLocal threadInterceptor = new ThreadLocal();    // Create the initial SessionFactory from the default configuration files
        static {
            try {
                configuration = new Configuration();
                sessionFactory = configuration.configure().buildSessionFactory();
                // We could also let Hibernate bind it to JNDI:
                // configuration.configure().buildSessionFactory()
            } catch (Throwable ex) {
                // We have to catch Throwable, otherwise we will miss
                // NoClassDefFoundError and other subclasses of Error
                log.error("Building SessionFactory failed.", ex);
                throw new ExceptionInInitializerError(ex);
            }
        }    /**
         * Returns the SessionFactory used for this static class.
         * 
         * @return SessionFactory
         */
        public static SessionFactory getSessionFactory() {
            // Instead of a static variable, use JNDI:
            // SessionFactory sessions = null;
            // try {
            // Context ctx = new InitialContext();
            // String jndiName = "java:hibernate/HibernateFactory";
            // sessions = (SessionFactory)ctx.lookup(jndiName);
            // } catch (NamingException ex) {
            // throw new InfrastructureException(ex);
            // }
            // return sessions;        return sessionFactory;
        }    /**
         * Returns the original Hibernate configuration.
         * 
         * @return Configuration
         */
        public static Configuration getConfiguration() {
            return configuration;
        }    /**
         * Rebuild the SessionFactory with the static Configuration.
         * 
         */
        public static void rebuildSessionFactory()
                throws ExceptionInInitializerError {
            synchronized (sessionFactory) {
                try {
                    sessionFactory = getConfiguration().buildSessionFactory();
                } catch (Exception ex) {
                    throw new ExceptionInInitializerError(ex);
                }
            }
        }    /**
         * Rebuild the SessionFactory with the given Hibernate Configuration.
         * 
         * @param cfg
         */
        public static void rebuildSessionFactory(Configuration cfg)
                throws ExceptionInInitializerError {
            synchronized (sessionFactory) {
                try {
                    sessionFactory = cfg.buildSessionFactory();
                    configuration = cfg;
                } catch (Exception ex) {
                    throw new ExceptionInInitializerError(ex);
                }
            }
        }    /**
         * Retrieves the current Session local to the thread.
         * <p/>
         * If no Session is open, opens a new Session for the running thread.
         * 
         * @return Session
         */
        public static Session getSession() throws ExceptionInInitializerError {
            Session s = (Session) threadSession.get();
            try {
                if (s == null) {
                    log.debug("Opening new Session for this thread.");
                    if (getInterceptor() != null) {
                        log.debug("Using interceptor: "
                                + getInterceptor().getClass());
                        s = getSessionFactory().openSession(getInterceptor());
                    } else {
                        s = getSessionFactory().openSession();
                    }
                    threadSession.set(s);
                }
            } catch (HibernateException ex) {
                throw new ExceptionInInitializerError(ex);
            }
            return s;
        }    /**
         * Closes the Session local to the thread.
         */
        public static void closeSession() throws ExceptionInInitializerError {
            try {
                Session s = (Session) threadSession.get();
                threadSession.set(null);
                if (s != null && s.isOpen()) {
                    log.debug("Closing Session of this thread.");
                    s.close();
                }
            } catch (HibernateException ex) {
                throw new ExceptionInInitializerError(ex);
            }
        }    /**
         * Start a new database transaction.
         */
        public static void beginTransaction() throws ExceptionInInitializerError {
            Transaction tx = (Transaction) threadTransaction.get();
            try {
                if (tx == null) {
                    log.debug("Starting new database transaction in this thread.");
                    tx = getSession().beginTransaction();
                    threadTransaction.set(tx);
                }
            } catch (HibernateException ex) {
                throw new ExceptionInInitializerError(ex);
            }
        }    /**
         * Commit the database transaction.
         */
        public static void commitTransaction() throws ExceptionInInitializerError {
            Transaction tx = (Transaction) threadTransaction.get();
            try {
                if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
                    log.debug("Committing database transaction of this thread.");
                    tx.commit();
                }
                threadTransaction.set(null);
            } catch (HibernateException ex) {
                rollbackTransaction();
                throw new ExceptionInInitializerError(ex);
            }
        }    /**
         * Commit the database transaction.
         */
        public static void rollbackTransaction() throws ExceptionInInitializerError {
            Transaction tx = (Transaction) threadTransaction.get();
            try {
                threadTransaction.set(null);
                if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
                    log.debug("Tyring to rollback database transaction of this thread.");
                    tx.rollback();
                }
            } catch (HibernateException ex) {
                throw new ExceptionInInitializerError(ex);
            } finally {
                closeSession();
            }
        }    /**
         * Reconnects a Hibernate Session to the current Thread.
         * 
         * @param session
         *            The Hibernate Session to be reconnected.
         */
        public static void reconnect(Session session)
                throws ExceptionInInitializerError {
            try {
                session.reconnect();
                threadSession.set(session);
            } catch (HibernateException ex) {
                throw new ExceptionInInitializerError(ex);
            }
        }    /**
         * Disconnect and return Session from current Thread.
         * 
         * @return Session the disconnected Session
         */
        public static Session disconnectSession()
                throws ExceptionInInitializerError {        Session session = getSession();
            try {
                threadSession.set(null);
                if (session.isConnected() && session.isOpen())
                    session.disconnect();
            } catch (HibernateException ex) {
                throw new ExceptionInInitializerError(ex);
            }
            return session;
        }    /**
         * Register a Hibernate interceptor with the current thread.
         * <p>
         * Every Session opened is opened with this interceptor after registration.
         * Has no effect if the current Session of the thread is already open,
         * effective on next close()/getSession().
         */
        public static void registerInterceptor(Interceptor interceptor) {
            threadInterceptor.set(interceptor);
        }    private static Interceptor getInterceptor() {
            Interceptor interceptor = (Interceptor) threadInterceptor.get();
            return interceptor;
        }}