论坛首页 Java企业应用论坛

struts 初始化 SessionFactory

浏览 8533 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2003-09-16  
HibernatePlugIn for Struts
To configure Hibernate in a Jakarta-Struts application:

1. Create your struts-config.xml file.

2. Add the following configuration for the plugin:

<plug-in className="edu.arbor.util.plugin.HibernatePlugIn">
  <!-- 'path-to-config-file' is relative to the root of the class
       path.  It MUST start with a '/'. The default is
       "/hibernate.cfg.xml -->
  <set-property property="configFilePath" value="path-to-config-file" />
  <set-property property="storeInServletContext" value="true-or-false" />
</plug-in>


3. Copy the code into a source file and compile.

package edu.arbor.util.plugin;

import java.net.URL;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;

/**
 * Implements the <code>PlugIn</code> interface to configure the Hibernate
 * data persistence library.  A configured
 * <code>net.sf.hibernate.SessionFactory</code> is stored in the 
 * <code>ServletContext</code> of the web application unless the property
 * <code>storedInServletContext</code> is set to <code>false</code>.
 * 
 * <p>
 * &plugin class=&net.sf.hibernate.plugins.struts.HibernatePlugIn&&
 *   &set-property name=&configFilePath""
 *                value=&path-to-config-file&/&
 *   &set-property name=&storedInServletContext""
 *                value=&true-or-false&/&
 * &/plugin&
 *
 * @author  <a href="mailto:bhandy@users.sf.net">Bradley M. Handy</a>
 * @version 1.0
 */
public class HibernatePlugIn implements PlugIn {
    
    /**
     * the key under which the <code>SessionFactory</code> instance is stored
     * in the <code>ServletContext</code>.
     */
    public static final String SESSION_FACTORY_KEY 
            = SessionFactory.class.getName();;

    private static Log _log = LogFactory.getLog(HibernatePlugIn.class);;
    
    /**
     * indicates whether the <code>SessionFactory</code> instance will be stored
     * in the <code>ServletContext</code>, or not.
     */
    private boolean _storedInServletContext = true;
    
    /**
     * the path to the xml configuration file.  the path should start with a
     * '/' character and be relative to the root of the class path.
     * (DEFAULT:  "/hibernate.cfg.xml");
     */
    private String _configFilePath = "/hibernate.cfg.xml";

    private ActionServlet _servlet = null;
    private ModuleConfig _config = null;
    private SessionFactory _factory = null;

    /**
     * Destroys the <code>SessionFactory</code> instance.
     */
    public void destroy(); {
        _servlet = null;
        _config = null;
        
        try {
            _log.debug("Destroying SessionFactory...");;
            
            _factory.close();;
            
            _log.debug("SessionFactory destroyed...");;
        } catch (Exception e); {
            _log.error("Unable to destroy SessionFactory...(exception ignored);",
                    e);;
        }
    }
    
    /**
     * Initializes the <code>SessionFactory</code>.
     * @param servlet the <code>ActionServlet</code> instance under which the
     *        plugin will run.
     * @param config the <code>ModuleConfig</code> for the module under which
     *        the plugin will run.
     */
    public void init(ActionServlet servlet, ModuleConfig config);
    throws ServletException {
        _servlet = servlet;
        _config = config;
        
        initHibernate();;
    }
    
    /**
     * Initializes Hibernate with the config file found at
     * <code>configFilePath</code>.
     */
    private void initHibernate(); throws ServletException {
        Configuration configuration = null;
        URL configFileURL = null;
        ServletContext context = null;
        
        try {
            configFileURL = HibernatePlugIn.class.getResource(_configFilePath);;

            context = _servlet.getServletContext();;

            if (_log.isDebugEnabled();); {
                _log.debug("Initializing Hibernate from "
                        + _configFilePath + "...");;
            }
            
            configuration = (new Configuration(););.configure(configFileURL);;
            _factory = configuration.buildSessionFactory();;
            
            if (_storedInServletContext); {
                _log.debug("Storing SessionFactory in ServletContext...");;
                
                context.setAttribute(SESSION_FACTORY_KEY, _factory);;
            }
           
        } catch (Throwable t); {
            _log.error("Exception while initializing Hibernate.");;
            _log.error("Rethrowing exception...", t);;
            
            throw (new ServletException(t););;
        }
    }
    
    /**
     * Setter for property configFilePath.
     * @param configFilePath New value of property configFilePath.
     */
    public void setConfigFilePath(String configFilePath); {
        if ((configFilePath == null); || (configFilePath.trim();.length(); == 0);); {
            throw new IllegalArgumentException(
                    "configFilePath cannot be blank or null.");;
        }
        
        if (_log.isDebugEnabled();); {
            _log.debug("Setting 'configFilePath' to '"
                    + configFilePath + "'...");;
        }
        
        _configFilePath = configFilePath;
    }
    
    /**
     * Setter for property storedInServletContext.
     * @param storedInServletContext New value of property storedInServletContext.
     */
    public void setStoredInServletContext(String storedInServletContext); {
        if ((storedInServletContext == null); 
                || (storedInServletContext.trim();.length(); == 0);); {
            storedInServletContext = "false";
        }
        
        if (_log.isDebugEnabled();); {
            _log.debug("Setting 'storedInServletContext' to '"
                    + storedInServletContext + "'...");;
        }
        
        _storedInServletContext 
                = new Boolean(storedInServletContext);.booleanValue();;
    }
    
}


这是从hibernate老家看到的
http://www.hibernate.org/105.html
可是我不知道如何在程序中调用已经储存的SessionFactory

    
   发表时间:2003-09-16  
帮帮我啊
0 请登录后投票
   发表时间:2003-09-16  
引用

if (_storedInServletContext) {
                _log.debug("Storing SessionFactory in ServletContext...");
               
                context.setAttribute(SESSION_FACTORY_KEY, _factory);
            }


SessionFactory sf=(SessionFactory);yourServletInstance.getServletContext();.getAttribute(HibernatePlugIn.SESSION_FACTORY_KEY);;
0 请登录后投票
   发表时间:2003-09-16  
在你的servlet中插入如下代码
ServletContext context = getServletContext();;
SessionFactory sessionFactory = (SessionFactory);context.getAttribute(HibernatePlugIn.SESSION_FACTORY_KEY);;
0 请登录后投票
   发表时间:2003-09-16  
那我要是再一个普通的类里里呢?
0 请登录后投票
   发表时间:2003-09-16  
zhenglinxi 写道
那我要是再一个普通的类里里呢?

反正要想方设法得到你的ServletContext
0 请登录后投票
   发表时间:2003-09-16  
那如果我在ejb里面调用的话,我怎么获得这个Factory啊,我想这个plugin只是适合只使用struts和jdbc的轻量级的应用的。
0 请登录后投票
   发表时间:2003-09-16  
mikeho 写道
那如果我在ejb里面调用的话,我怎么获得这个Factory啊,我想这个plugin只是适合只使用struts和jdbc的轻量级的应用的。


这个plug in适合在单独的web application中使用,如果在EJB中调用Hibernate的SessionFactoryImpl,那么应该把Hibernate配置到App Server上的JNDI上,看看精华区,有文章讲怎么在weblogic上把SessionFactoryImpl配置为JNDI
0 请登录后投票
   发表时间:2003-09-17  
是的,我的做法就是bind到jndi上面
0 请登录后投票
论坛首页 Java企业应用版

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