`
maybe723
  • 浏览: 44933 次
  • 来自: ...
最近访客 更多访客>>
社区版块
存档分类
最新评论

HibernateUtil

阅读更多
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;

    static {
        try {
            // Create the SessionFactory
            sessionFactory = new Configuration().configure("/hibernate.cfg.xml")
                    .buildSessionFactory();
        } catch (Throwable ex) {
            ex.printStackTrace();
            System.out.println("Initial SessionFactory creation failed.");
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static final ThreadLocal tLocalsess = new ThreadLocal();

    public static final ThreadLocal tLocaltx = new ThreadLocal();

    /*
     * getting the thread-safe session for using
     */
    public static Session currentSession() {
        Session session = (Session) tLocalsess.get();

        //open a new one, if none can be found.
        try {
            if (session == null || !session.isOpen()) {
                session = openSession();
                tLocalsess.set(session);
            }
        } catch (HibernateException e) {
            //throw new HibernateException(e);
            e.printStackTrace();
        }
        return session;
    }

    /*
     * closing the thread-safe session
     */
    public static void closeSession() {

        Session session = (Session) tLocalsess.get();
        tLocalsess.set(null);
        try {
            if (session != null && session.isOpen()) {
                session.close();
            }

        } catch (HibernateException e) {
            //throw new InfrastructureException(e);
        }
    }

    /*
     * begin the transaction
     */
    public static void beginTransaction() {
        System.out.println("begin tx");
        Transaction tx = (Transaction) tLocaltx.get();
        try {
            if (tx == null) {
                tx = currentSession().beginTransaction();
                tLocaltx.set(tx);
            }
        } catch (HibernateException e) {
            //throw new InfrastructureException(e);
        }
    }

    /*
     * close the transaction
     */
    public static void commitTransaction() {
        Transaction tx = (Transaction) tLocaltx.get();
        try {
            if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack())
                tx.commit();
            tLocaltx.set(null);
             } catch (HibernateException e) {
            //throw new InfrastructureException(e);
        }
    }

    /*
     * for rollbacking
     */
    public static void rollbackTransaction() {
        Transaction tx = (Transaction) tLocaltx.get();
        try {
            tLocaltx.set(null);
            if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
                tx.rollback();
            }
        } catch (HibernateException e) {
            //throw new InfrastructureException(e);
        }
    }

    private static Session openSession() throws HibernateException {
        return getSessionFactory().openSession();
    }

    private static SessionFactory getSessionFactory() throws HibernateException {
        return sessionFactory;//SingletonSessionFactory.getInstance();
    }
}

 

  在Dao中:

  打开一个session后,不关闭这个session,否则在级联的情况下可能会产生org.hibernate.LazyInitializationException:

所以定义一个过滤器:

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class CloseSessionFilter implements Filter {
	Log logger = LogFactory.getLog(this.getClass());
	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	protected FilterConfig config;
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		this.config = arg0;
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(
		ServletRequest request,
		ServletResponse response,
		FilterChain chain)
		throws IOException, ServletException {
		// TODO Auto-generated method stub
		try{
			chain.doFilter((HttpServletRequest)request, (HttpServletResponse)response);
		}
		finally{
			try{
				HibernateUtil.commitTransaction();
			}catch (Exception e){
				HibernateUtil.rollbackTransaction();
			}finally{
				HibernateUtil.closeSession();
			}   
		}
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
		this.config = null;
	}

}

  

    在web.xml中配置:

<filter>
	<filter-name>closeSessionFilter</filter-name>
		<filter-class>
			utils.CloseSessionFilter
		</filter-class>
</filter>
<filter-mapping>
		<filter-name>closeSessionFilter</filter-name>
		<url-pattern>/*</url-pattern>
</filter-mapping>

 

而到了spring 中,在web.xml配置:

<filter>
	<filter-name>openSession</filter-name>
	<filter-class>
	org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
	</filter-class>
</filter>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics