摘自:http://forum.javaeye.com/viewtopic.php?t=1751
我們之前寫了一個HibernateUitl的類,專門用于Hibernate Session的維護,它的代碼如下:
package com.huangdong.demo.util;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory =
new Configuration().configure().buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException(
"Exception building SessionFactory: " + ex.getMessage(),
ex);
}
}
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws HibernateException {
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() throws HibernateException {
Session s = (Session) session.get();
session.set(null);
if (s != null)
s.close();
}
}
下面我們對這段代碼中我們需要關注的內容進行細致的說明。首先,這個類的目標有兩個:
單一實例:在系統中全局使用一個唯一的SessionFactory實 例。主要的原因一是Factory只需要一個實例可以調用方法就可以;另一方面取得SessionFActory需要的時間太久,每次都實例化,會過分浪費系統CPU資源。
每個線和使用自身對應的數據庫連接session:這里是為每個線程建立了一個局部的變量來達到這個目的。
需要Plugin所做的事
單一實例的實線是依靠下面的代碼:
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory =
new Configuration().configure().buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException(
"Exception building SessionFactory: " + ex.getMessage(),
ex);
}
}
一個局部靜態變量sessionFactory是整個application使用的唯一的一個實例,它在類第一次調入內存時通過
sessionFactory = new Configuration().configure().buildSessionFactory();
將自己實例化。這個實例化的過程比較漫長。很顯然,這個操作與通常我們使用Servlet時要在Servlet調入內存時初始化的init()方法所能做到的事很相似。在Struts中提供了Plugin這么一個機制來擴充Struts的基礎功能,其實Plugin的實現也是基于Servlet的init方法和destory方法的。
總結起來,就是在Web應用這個特殊的環境中,由其是Struts中(因為它使用的Servlet只是一個,或說只是一個類及該類的子類)我們完全可以利用Servlet的init/destory機制(也就是Plugin機制)來完成在Web應用啟動時的SessionFactory初始化和Web應用停止時SessionFactory的清除工作。
但是同時也會發現,如果在Plugin中對SessionFactory進行實例化后,無法將該實例傳輸給使用者,但是Web應用環境中也給我們可以使用以下解決辦法:
JNDI
Plugin的靜態方法/變量
ServletContex t的Attribute
下面我們以使用JNDI為主說明這些SessionFactory使用的模式。
Plugin To JNDI
通過JNDI完成SessionFactory的初始化的思路基本上是這樣的:
在一個Plugin的init方法中初始化SessionFactory的實例
初始化完成后將SessionFactory的實例bind到JNDI目錄樹的一個節點上
返回init方法
在所有要使用SessionFactory的地方通過JNDI lookup出sessionFactory的實例得到具體的session進行數據庫操作
在Plugin的destory方法是unbind節點,并將SessionFactory的實例清除
以下是具體的代碼片段,首先我們看看Plugin中的相關代碼:
/*
* 創建日期 2003-12-26
*/
package com.huangdong.demo.plugin;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
/**
* @author HD
*/
public class InitHibernate implements PlugIn {
private Context ctx;
private SessionFactory sessionFactory;
/*
* 插件銷毀方法
*/
public void destroy() {
if (ctx != null) {
try {
// unbind JNDI 節點
ctx.unbind("HibernateSessionFactory");
} catch (NamingException e) {
e.printStackTrace();
}
}
if (sessionFactory != null) {
try {
// 關閉sessionFactory
sessionFactory.close();
} catch (HibernateException e) {
e.printStackTrace();
}
sessionFactory = null;
}
}
/*
* 插件初始化方法
*/
public void init(ActionServlet servlet, ModuleConfig config)
throws ServletException {
try {
// 獲取SessionFactory的實例
sessionFactory =
new Configuration().configure().buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException(
"Exception building SessionFactory: " + ex.getMessage(),
ex);
}
try {
// 取得容器上下文
ctx = new InitialContext();
// 將sessionFactory bind到JND樹中
ctx.bind("HibernateSessionFactory", sessionFactory);
} catch (NamingException ex) {
throw new RuntimeException(
"Exception binding SessionFactory to JNDI: " + ex.getMessage(),
ex);
}
}
}
接下來我們改造一下原來的HibernateUitl類,我們新建一個HibernateUtilPlus類:
/*
* 創建日期 2003-12-28
*
*/
package com.huangdong.demo.util;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
/**
* @author HD
*/
public class HibernateUtilPlus {
private static SessionFactory sessionFactory = null;
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws HibernateException {
if (sessionFactory == null) {
// 如果sessionFactory實例為null則從JNDI中獲取
if (getSystemSessionFactory() == false) {
throw new HibernateException("Exception geting SessionFactory from JNDI ");
}
}
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() throws HibernateException {
Session s = (Session) session.get();
session.set(null);
if (s != null)
s.close();
}
private static boolean getSystemSessionFactory() {
try {
//從JNDI中取得SessionFactory的實例,如果出錯返回false
Context inttex = new InitialContext();
sessionFactory =
(SessionFactory) inttex.lookup("HibernateSessionFactory");
} catch (NamingException e) {
return false;
}
return true;
}
}
這里有一個getSystemSessionFactory方法專門從JNDI中獲取SessionFactory的實例。
我們還是使用之前的TestServlet來測試,改過之后的TestServlet類如下:
/*
* 創建日期 2003-12-26
*
*/
package com.huangdong.demo.bean;
import java.util.Calendar;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import com.huangdong.demo.dao.SysUser;
import com.huangdong.demo.util.HibernateUtilPlus;
/**
* @author HD
*/
public class TestHibernate {
public TestHibernate() {
}
public boolean TestAdd() {
try {
Session session = HibernateUtilPlus.currentSession();
Transaction tx = session.beginTransaction();
SysUser user = new SysUser();
user.setUsername("丫丫2");
user.setUserpasword("uhkuhkqepdwqi");
user.setLastlogin(Calendar.getInstance());
session.save(user);
tx.commit();
HibernateUtilPlus.closeSession();
} catch (HibernateException e) {
e.printStackTrace();
return false;
}
return true;
}
}
這里使用HibernateUtilPlus類來獲取session。
最后我們需要將寫好的Plugin配置到Struts中去,以讓應用服務器啟動時識別到這個Plugin的存在以初始化相關的內容。在WEB-INF文件夾下有一個名為struts-config.xml的配置文件,在其中加入Plugin的配置:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<data-sources />
<form-beans >
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings >
</action-mappings>
<controller />
<message-resources parameter="com.huangdong.demo.ApplicationResources" />
<!--加入Plugin的配置,使用plug-in元素進行說明-->
<plug-in className="com.huangdong.demo.plugin.InitHibernate" />
</struts-config>
再次運行Tomcat,進行測試??梢栽?這里下載 通過JNDI Plugin的Eclipse示例。
另兩種方法的探索
在文章的最開始,我們提到了三種方法,除了上面仔細提到的還有另外兩種:
Plugin的靜態方法/變量
ServletContext的Attribute
這里我們簡單說明這兩種方法實現的原理,就不實際的完成具體代碼了。具體的代碼與測試還請讀者自己完成。
Plugin的靜態方法和變量
使用這種方法與使用原有的HibernateUtil類的原理類似,但是可以將SessionFaction的實例化放在init方法中。如下:
/*
* 創建日期 2003-12-26
*/
package com.huangdong.demo.plugin;
import javax.servlet.ServletException;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
/**
* @author HD
*/
public class InitHibernate implements PlugIn {
public static final SessionFactory sessionFactory;
/*
* 插件銷毀方法
*/
public void destroy() {
sessionFactory = null;
}
}
/*
* 插件初始化方法
*/
public void init(ActionServlet servlet, ModuleConfig config)
throws ServletException {
try {
// 獲取SessionFactory的實例
sessionFactory =
new Configuration().configure().buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException(
"Exception building SessionFactory: " + ex.getMessage(),
ex);
}
}
}
這段plugin代碼很簡單,在使用時也就直接使用這個Plugin的public變量來取得sessionFactroy實例了。
ServletContext的Attribute
這個方法的原理基于對Servlet的使用,在Struts 中的使用會麻煩。它的原理是這樣的:
首先在plugin中初始化好sessionFactory實例,使用這兩句話將其放入servlet的context中:
ServletContext context = servlet.getServletContext();
context.setAttribute("SESSIONFACTORY", sessionFactory);
使用的方法很簡單了,就是擴展一個自定義的ActionServlet,在提交具體的Action前,將SessionFactory提取出來,放入調用Action的execute方法的參數request的屬性中。代碼如下:
ServletContext context = servlet.getServletContext();
context.getAttribute("SESSIONFACTORY", sessionFactory);
request.setAttribute("SESSIONFACTORY", sessionFactory);
這樣在具體的execute方法里可以通過:
request.getAttribute("SESSIONFACTORY", sessionFactory);
來取到正確的SessionFactory。
這里的實現方法都是原理性的,具體還需要大家仔細了解Struts的實現方法來總結出自己最為習慣的使用策略。
留在最后話
本文中的所有代碼在以下環境中由作者實際測試完全沒有問題:
Eclipse 2.1.2
Struts 1.1
Hibernate 2.1.1
Tomcat 4.1.29/Jetty 4.2.15/Orion 2.0.2
com.tanghan.plugin_0.1.0.12.21
JDK 1.4.2_02 For Windows/FreeBSD 4.8/FreeBSD 4.9
FreeBSD 4.8/FreeBSD 4.9/Windows 2000/Windows XP
Oracle 9.2.0.1.0
如果你對本文有什么意見和建議請 聯系我 ,告訴我你的想法,另外也可以到 技術天空BBS的Java版 中討論與Java相關的各種技術。
我們之前寫了一個HibernateUitl的類,專門用于Hibernate Session的維護,它的代碼如下:
package com.huangdong.demo.util;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory =
new Configuration().configure().buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException(
"Exception building SessionFactory: " + ex.getMessage(),
ex);
}
}
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws HibernateException {
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() throws HibernateException {
Session s = (Session) session.get();
session.set(null);
if (s != null)
s.close();
}
}
下面我們對這段代碼中我們需要關注的內容進行細致的說明。首先,這個類的目標有兩個:
單一實例:在系統中全局使用一個唯一的SessionFactory實 例。主要的原因一是Factory只需要一個實例可以調用方法就可以;另一方面取得SessionFActory需要的時間太久,每次都實例化,會過分浪費系統CPU資源。
每個線和使用自身對應的數據庫連接session:這里是為每個線程建立了一個局部的變量來達到這個目的。
需要Plugin所做的事
單一實例的實線是依靠下面的代碼:
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory =
new Configuration().configure().buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException(
"Exception building SessionFactory: " + ex.getMessage(),
ex);
}
}
一個局部靜態變量sessionFactory是整個application使用的唯一的一個實例,它在類第一次調入內存時通過
sessionFactory = new Configuration().configure().buildSessionFactory();
將自己實例化。這個實例化的過程比較漫長。很顯然,這個操作與通常我們使用Servlet時要在Servlet調入內存時初始化的init()方法所能做到的事很相似。在Struts中提供了Plugin這么一個機制來擴充Struts的基礎功能,其實Plugin的實現也是基于Servlet的init方法和destory方法的。
總結起來,就是在Web應用這個特殊的環境中,由其是Struts中(因為它使用的Servlet只是一個,或說只是一個類及該類的子類)我們完全可以利用Servlet的init/destory機制(也就是Plugin機制)來完成在Web應用啟動時的SessionFactory初始化和Web應用停止時SessionFactory的清除工作。
但是同時也會發現,如果在Plugin中對SessionFactory進行實例化后,無法將該實例傳輸給使用者,但是Web應用環境中也給我們可以使用以下解決辦法:
JNDI
Plugin的靜態方法/變量
ServletContex t的Attribute
下面我們以使用JNDI為主說明這些SessionFactory使用的模式。
Plugin To JNDI
通過JNDI完成SessionFactory的初始化的思路基本上是這樣的:
在一個Plugin的init方法中初始化SessionFactory的實例
初始化完成后將SessionFactory的實例bind到JNDI目錄樹的一個節點上
返回init方法
在所有要使用SessionFactory的地方通過JNDI lookup出sessionFactory的實例得到具體的session進行數據庫操作
在Plugin的destory方法是unbind節點,并將SessionFactory的實例清除
以下是具體的代碼片段,首先我們看看Plugin中的相關代碼:
/*
* 創建日期 2003-12-26
*/
package com.huangdong.demo.plugin;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
/**
* @author HD
*/
public class InitHibernate implements PlugIn {
private Context ctx;
private SessionFactory sessionFactory;
/*
* 插件銷毀方法
*/
public void destroy() {
if (ctx != null) {
try {
// unbind JNDI 節點
ctx.unbind("HibernateSessionFactory");
} catch (NamingException e) {
e.printStackTrace();
}
}
if (sessionFactory != null) {
try {
// 關閉sessionFactory
sessionFactory.close();
} catch (HibernateException e) {
e.printStackTrace();
}
sessionFactory = null;
}
}
/*
* 插件初始化方法
*/
public void init(ActionServlet servlet, ModuleConfig config)
throws ServletException {
try {
// 獲取SessionFactory的實例
sessionFactory =
new Configuration().configure().buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException(
"Exception building SessionFactory: " + ex.getMessage(),
ex);
}
try {
// 取得容器上下文
ctx = new InitialContext();
// 將sessionFactory bind到JND樹中
ctx.bind("HibernateSessionFactory", sessionFactory);
} catch (NamingException ex) {
throw new RuntimeException(
"Exception binding SessionFactory to JNDI: " + ex.getMessage(),
ex);
}
}
}
接下來我們改造一下原來的HibernateUitl類,我們新建一個HibernateUtilPlus類:
/*
* 創建日期 2003-12-28
*
*/
package com.huangdong.demo.util;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
/**
* @author HD
*/
public class HibernateUtilPlus {
private static SessionFactory sessionFactory = null;
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws HibernateException {
if (sessionFactory == null) {
// 如果sessionFactory實例為null則從JNDI中獲取
if (getSystemSessionFactory() == false) {
throw new HibernateException("Exception geting SessionFactory from JNDI ");
}
}
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() throws HibernateException {
Session s = (Session) session.get();
session.set(null);
if (s != null)
s.close();
}
private static boolean getSystemSessionFactory() {
try {
//從JNDI中取得SessionFactory的實例,如果出錯返回false
Context inttex = new InitialContext();
sessionFactory =
(SessionFactory) inttex.lookup("HibernateSessionFactory");
} catch (NamingException e) {
return false;
}
return true;
}
}
這里有一個getSystemSessionFactory方法專門從JNDI中獲取SessionFactory的實例。
我們還是使用之前的TestServlet來測試,改過之后的TestServlet類如下:
/*
* 創建日期 2003-12-26
*
*/
package com.huangdong.demo.bean;
import java.util.Calendar;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import com.huangdong.demo.dao.SysUser;
import com.huangdong.demo.util.HibernateUtilPlus;
/**
* @author HD
*/
public class TestHibernate {
public TestHibernate() {
}
public boolean TestAdd() {
try {
Session session = HibernateUtilPlus.currentSession();
Transaction tx = session.beginTransaction();
SysUser user = new SysUser();
user.setUsername("丫丫2");
user.setUserpasword("uhkuhkqepdwqi");
user.setLastlogin(Calendar.getInstance());
session.save(user);
tx.commit();
HibernateUtilPlus.closeSession();
} catch (HibernateException e) {
e.printStackTrace();
return false;
}
return true;
}
}
這里使用HibernateUtilPlus類來獲取session。
最后我們需要將寫好的Plugin配置到Struts中去,以讓應用服務器啟動時識別到這個Plugin的存在以初始化相關的內容。在WEB-INF文件夾下有一個名為struts-config.xml的配置文件,在其中加入Plugin的配置:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<data-sources />
<form-beans >
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings >
</action-mappings>
<controller />
<message-resources parameter="com.huangdong.demo.ApplicationResources" />
<!--加入Plugin的配置,使用plug-in元素進行說明-->
<plug-in className="com.huangdong.demo.plugin.InitHibernate" />
</struts-config>
再次運行Tomcat,進行測試??梢栽?這里下載 通過JNDI Plugin的Eclipse示例。
另兩種方法的探索
在文章的最開始,我們提到了三種方法,除了上面仔細提到的還有另外兩種:
Plugin的靜態方法/變量
ServletContext的Attribute
這里我們簡單說明這兩種方法實現的原理,就不實際的完成具體代碼了。具體的代碼與測試還請讀者自己完成。
Plugin的靜態方法和變量
使用這種方法與使用原有的HibernateUtil類的原理類似,但是可以將SessionFaction的實例化放在init方法中。如下:
/*
* 創建日期 2003-12-26
*/
package com.huangdong.demo.plugin;
import javax.servlet.ServletException;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
/**
* @author HD
*/
public class InitHibernate implements PlugIn {
public static final SessionFactory sessionFactory;
/*
* 插件銷毀方法
*/
public void destroy() {
sessionFactory = null;
}
}
/*
* 插件初始化方法
*/
public void init(ActionServlet servlet, ModuleConfig config)
throws ServletException {
try {
// 獲取SessionFactory的實例
sessionFactory =
new Configuration().configure().buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException(
"Exception building SessionFactory: " + ex.getMessage(),
ex);
}
}
}
這段plugin代碼很簡單,在使用時也就直接使用這個Plugin的public變量來取得sessionFactroy實例了。
ServletContext的Attribute
這個方法的原理基于對Servlet的使用,在Struts 中的使用會麻煩。它的原理是這樣的:
首先在plugin中初始化好sessionFactory實例,使用這兩句話將其放入servlet的context中:
ServletContext context = servlet.getServletContext();
context.setAttribute("SESSIONFACTORY", sessionFactory);
使用的方法很簡單了,就是擴展一個自定義的ActionServlet,在提交具體的Action前,將SessionFactory提取出來,放入調用Action的execute方法的參數request的屬性中。代碼如下:
ServletContext context = servlet.getServletContext();
context.getAttribute("SESSIONFACTORY", sessionFactory);
request.setAttribute("SESSIONFACTORY", sessionFactory);
這樣在具體的execute方法里可以通過:
request.getAttribute("SESSIONFACTORY", sessionFactory);
來取到正確的SessionFactory。
這里的實現方法都是原理性的,具體還需要大家仔細了解Struts的實現方法來總結出自己最為習慣的使用策略。
留在最后話
本文中的所有代碼在以下環境中由作者實際測試完全沒有問題:
Eclipse 2.1.2
Struts 1.1
Hibernate 2.1.1
Tomcat 4.1.29/Jetty 4.2.15/Orion 2.0.2
com.tanghan.plugin_0.1.0.12.21
JDK 1.4.2_02 For Windows/FreeBSD 4.8/FreeBSD 4.9
FreeBSD 4.8/FreeBSD 4.9/Windows 2000/Windows XP
Oracle 9.2.0.1.0
如果你對本文有什么意見和建議請 聯系我 ,告訴我你的想法,另外也可以到 技術天空BBS的Java版 中討論與Java相關的各種技術。