论坛首页 Java企业应用论坛

在filter里关闭session

浏览 17911 次
该帖已经被评为精华帖
作者 正文
   发表时间:2003-12-18  
package com.upstate.cellculture.om.persist;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.JDBCException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;

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

/**
 * This class is used to get Hibernate Sessions and may
 * also contain methods (in the future); to get DBConnections
 * or Transactions from JNDI.
 */
public class ServiceLocator
{
    //~ Static fields/initializers =============================================
    public final static String SESSION_FACTORY = "hibernate/sessionFactory";
    public static final ThreadLocal session = new ThreadLocal();;
    private static SessionFactory sf = null;
    private static ServiceLocator me;
    private static Log log = LogFactory.getLog(ServiceLocator.class);;

    static {
        try
        {
            me = new ServiceLocator();;
        }
        catch (Exception e);
        {
            log.fatal("Error occurred initializing ServiceLocator");;
            e.printStackTrace();;
        }
    }

    //~ Constructors ===========================================================

    private ServiceLocator(); throws HibernateException, JDBCException
    {}

    //~ Methods ================================================================

    public static Session currentSession(); throws PersistenceException
    {
        Session s = (Session); session.get();;

        if (s == null);
        {
            s = PersistenceManager.openSession();;
            if (log.isDebugEnabled(););
            {
                log.debug("Opened hibernate session.");;
            }

            session.set(s);;
        }

        return s;
    }

    public static void closeSession(); throws HibernateException, JDBCException
    {
        Session s = (Session); session.get();;
        session.set(null);;

        if (s != null);
        {
            if (s.isOpen(););
            {
                s.flush();;
                s.close();;

                if (log.isDebugEnabled(););
                {
                    log.debug("Closed hibernate session.");;
                }
            }
        }
        else
        {
            log.warn("Hibernate session was inadvertently already closed.");;

        }
    }
}


如果你使用对象的lazy loading你需要使用一个servlet filter
package com.upstate.cellculture.filter;

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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.hibernate.Session;

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

import com.upstate.cellculture.om.persist.PersistenceException;
import com.upstate.cellculture.om.persist.ServiceLocator;

public class ActionFilter implements Filter
{
    //~ Static fields/initializers =============================================

    //~ Instance fields ========================================================

    /**
     * The <code>Log</code> instance for this class
     */
    private Log log = LogFactory.getLog(ActionFilter.class);;
    private FilterConfig filterConfig = null;

    //~ Methods ================================================================

    public void init(FilterConfig filterConfig); throws ServletException
    {
        this.filterConfig = filterConfig;

    }

    /**
     * Destroys the filter.
     */
    public void destroy();
    {
        filterConfig = null;
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain); throws IOException, ServletException
    {
        // cast to the types I want to use
        HttpServletRequest request = (HttpServletRequest); req;
        HttpServletResponse response = (HttpServletResponse); resp;
        HttpSession session = request.getSession(true);;

        Session ses = null;
        boolean sessionCreated = false;

        try
        {
            chain.doFilter(request, response);;
        }
        finally
        {
            try
            {
                ServiceLocator.closeSession();;
            }
            catch (Exception exc);
            {
                log.error("Error closing hibernate session.", exc);;
                exc.printStackTrace();;
            }
        }
    }

    public static Session getSession(); throws PersistenceException
    {
        try
        {

            return ServiceLocator.currentSession();;
        }
        catch (Exception e);
        {
            throw new PersistenceException("Could not find current Hibernate session.", e);;
        }

    }
}


此外,为了把数据库访问集中起来,我们会使用一些manager类,也就是DAO
/*
 * Created on Apr 28, 2003
 *
 */
package com.upstate.cellculture.om.persist;
import java.util.List;

import net.sf.hibernate.Query;
import net.sf.hibernate.Session;

import com.upstate.cellculture.om.Technician;
/**
 * @author tmckinney
 *
 * Centralizes all access to the Technicians table
 */
public class TechnicianManager
{
    private static List allTechnicians;
    public static void save(Technician technician); throws PersistenceException
    {
        try
        {

            ServiceLocator.currentSession();.save(technician);;

        }
        catch (Exception e);
        {
            throw new PersistenceException("Could not save.", e);;
        }
    }

    public static Technician retrieveByPK(long technicianId); throws PersistenceException
       {
           try
             {
                 Technician technician= (Technician); ServiceLocator.currentSession();.load(Technician.class, new Long(technicianId););;
                 return technician;
             }
             catch (Exception e);
             {
                 throw new PersistenceException("Could not retrieve.", e);;
             }
       }


    public static List retrieveAllTechnicians(); throws PersistenceException
    {
        if (allTechnicians == null);
        {
            try
            {
                Query q = ServiceLocator.currentSession();.createQuery("from technician in class " + Technician.class +" order by upper(technician.name);");;
                allTechnicians = q.list();;
                session.flush();;
            }
            catch (Exception e);
            {
                e.printStackTrace();;
                throw new PersistenceException(e);;
            }
        }
        return allTechnicians;

    }


}


如果能够使用一个 TechnicianManager接口和一个TechnicianManagerImpl class. 那就更好了。

通过自己定义的一个异常来包装了所有抛出的异常。

package com.upstate.cellculture.om.persist;

import org.apache.commons.lang.exception.NestableException;
/**
 * A general PersistenceException that is thrown by all Manager classes.
 *
 */
public class PersistenceException extends NestableException
{
    //~ Constructors ===========================================================

    /**
     * Constructor for PersistenceException.
     */
    public PersistenceException();
    {
        super();;
    }

    /**
     * Constructor for PersistenceException.
     *
     * @param message
     */
    public PersistenceException(String message);
    {
        super(message);;
    }

    /**
     * Constructor for PersistenceException.
     *
     * @param message
     * @param cause
     */
    public PersistenceException(String message, Throwable cause);
    {
        super(message, cause);;
    }

    /**
     * Constructor for PersistenceException.
     *
     * @param cause
     */
    public PersistenceException(Throwable cause);
    {
        super(cause);;
    }

}

   发表时间:2004-01-07  
static {
        try
        {
            me = new ServiceLocator(); //能这么创建实例吗?
        }
        catch (Exception e)
        {
            log.fatal("Error occurred initializing ServiceLocator");
            e.printStackTrace();
        }
    }
//~ Constructors ===========================================================

    private ServiceLocator() throws HibernateException, JDBCException
    {}


麻烦拷贝jakarta turbine代码的时候看看别人是不是有笔误:)
最好也写上出处。
0 请登录后投票
   发表时间:2004-01-29  
jaqwolf 写道
static {
        try
        {
            me = new ServiceLocator(); //能这么创建实例吗?
        }
        catch (Exception e)
        {
            log.fatal("Error occurred initializing ServiceLocator");
            e.printStackTrace();
        }
    }
//~ Constructors ===========================================================

    private ServiceLocator() throws HibernateException, JDBCException
    {}


麻烦拷贝jakarta turbine代码的时候看看别人是不是有笔误:)
最好也写上出处。


首先在这里致歉,没有把出处标明,实在是太懒了,该打:)

此外,这位仁兄大概很少看到静态初始化块吧,我这次从sun的官方教材上摘了一段,请这位仁兄再指点一二。

引用

Using Static Initialization Blocks
Here's an example of a static initialization block:

import java.util.ResourseBundle;
class Errors{
static ResourceBundle errorStrings;
static{
        try{
               errorString=ResourceBundle.getBundle("ErrorStrings");;
     }catch(java.util.MissingResourceBundle);
      {
           //do something
      }
}


The errorStrings resource bundle must be initialized in a static initialization block. This is because error recovery must be performed if the bundle cannot be found. Also, errorStrings is a class member and it doesn't make sense for it to be initialized in a constructor. As the previous example shows, a static initialization block begins with the static keyword and is a normal block of Java code enclosed in curly braces {}.
A class can have any number of static initialization blocks that appear anywhere in the class body. The runtime system guarantees that static initialization blocks and static initializers are called in the order (left-to-right, top-to-bottom) that they appear in the source code
0 请登录后投票
   发表时间:2004-02-04  
我试了一下,是我弄错了一个基本的概念。
0 请登录后投票
   发表时间:2004-02-12  
引用
为了把数据库访问集中起来,我们会使用一些manager类,也就是DAO 。


按我理解,manager应该是service layer层的,其概念不等同于DAO,DAO是更底层的东西(是对jdbc rowset方法的封装).
关于service layer可一看看Spring Framework.
0 请登录后投票
   发表时间:2004-02-12  
能不能介绍几篇好的spring framework的文章
0 请登录后投票
   发表时间:2004-02-20  
用spring管理hibernate不错,不用在Action中向后传actionFilter.也不需要ServiceLocator了。
0 请登录后投票
   发表时间:2004-02-20  
如果是这样岂不是要每个Po都要写一个manager类,加个DAO会比较好一些,manager使用dao中的方法而不是直接操纵session
0 请登录后投票
   发表时间:2004-02-26  
//~ Methods ================================================================ 

    public static Session currentSession(); throws PersistenceException 
    { 
        Session s = (Session); session.get();; 

        if (s == null); 
        { 
            s = PersistenceManager.openSession();; 
            if (log.isDebugEnabled();); 
            { 
                log.debug("Opened hibernate session.");; 
            } 

            session.set(s);; 
        } 

        return s; 
    } 


这样的话是没法使用的啊?
0 请登录后投票
   发表时间:2004-02-26  
这篇代码的主要意图有二:
1。是通过静态初始化块来初始化hibernate configuration并使整个jvm中只存在一个SessionFactory对象。
2。使用filter来实现一个session可以在页面显示以后再关闭。
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics