转贴--Hibernate Session的维护

类别:Java 点击:0 评论:0 推荐:
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

本文地址:http://com.8s8s.com/it/it13088.htm