文档章节

Spring+Hibernate整合Hessian

dexterman
 dexterman
发布于 2013/07/30 10:19
字数 727
阅读 949
收藏 2

软件环境: JDK1.6、Spring3.0.5、Hibernate3.2.2、Hessian3.1.5

参考Spring Documents:中文|英文

服务端:

###1. remoting-servlet.xml <!-- 扫描并加注HessianService使用的bean --> <context:annotation-config /> <!-- <context:component-scan base-package="com.**" /> -->

<!--Hessian 启动BeanNameMapping 映射功能,以httpRequest作为处理Adapter-->
<!-- <bean
    class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
    <property name="defaultHandler" ref="httpRequestHandlerAdapter" />
</bean> -->

<!-- Hessian 方式以Http进行传递 -->
<!-- <bean id="httpRequestHandlerAdapter" class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter" /> -->
    
    <!-- 解决Hibernate实体对象bean中集合对象延迟加载lazyLoad,
        导致Hessian客户端抛出no session or session closed异常的问题 -->
<bean id="lazySerializer" class="com.test.webservice.LazyHibernateSerializerFactory"></bean>

<!-- UnifiedUser -->
<bean id="unifiedUserService" class="com.test.manager.impl.UnifiedUserServiceImpl" />
<bean name="/UnifiedUserService" class="org.springframework.remoting.caucho.HessianServiceExporter">
	<property name="serializerFactory" ref="lazySerializer"/>
	<property name="service" ref="unifiedUserService" />
	<property name="serviceInterface" value="com.test.manager.UnifiedUserService"/>
</bean>

###2. LazyHibernateSerializerFactory实现
参考: https://github.com/resthub/spring-amqp-hessian/issues/5

引用: http://code.google.com/p/rich-hibernate-lazy/wiki/HessianWithLazyHibernate

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.Hibernate;
import org.hibernate.collection.PersistentList;
import org.hibernate.collection.PersistentMap;
import org.hibernate.collection.PersistentSet;

import com.caucho.hessian.io.AbstractHessianOutput;
import com.caucho.hessian.io.CollectionSerializer;
import com.caucho.hessian.io.HessianProtocolException;
import com.caucho.hessian.io.JavaSerializer;
import com.caucho.hessian.io.MapSerializer;
import com.caucho.hessian.io.Serializer;
import com.caucho.hessian.io.SerializerFactory;

/**
 * 处理:Hessian远程调用时,对象序列化hibernate实体bean中集合对象延迟加载问题 ,
 * 		采取将集合对象替换为空集合。
 * 
 *
 */
public class LazyHibernateSerializerFactory extends SerializerFactory {
	public static   String versionString = org.hibernate.Version.getVersionString();
	
	@Override
	public Serializer getSerializer(Class cls) throws HessianProtocolException {
		try {
			if(versionString.startsWith("3") &&Class.forName("org.hibernate.collection.PersistentCollection")
                    .isAssignableFrom(cls)){
				return new LazySerializerForHibernate3(cls); 
			}else if(versionString.startsWith("4") &&   
    Class.forName("org.hibernate.collection.spi.PersistentCollection").isAssignableFrom(cls)){
				return new LazySerializerForHibernate4(cls); 
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		return super.getSerializer(cls);
	}
}

class LazySerializerForHibernate3 extends JavaSerializer {

	public LazySerializerForHibernate3(Class cls) {
		super(cls);
	}
	
	CollectionSerializer collectionSeiralizer = new CollectionSerializer();
	MapSerializer mapSerializer = new MapSerializer();

	/**
	 * @Title: writeObject
	 * @Description: TODO(override hessian write)
	 * @param @param object
	 * @param @param out
	 * @param @throws IOException
	 * @return void
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void writeObject(Object object, AbstractHessianOutput out)
			throws IOException {

		boolean ifHaveInit = Hibernate.isInitialized(object);
		Object obj = convertPersistent(object);
		if (ifHaveInit && object!=null) {
			out.writeObject(obj);  
            out.flush();
			return;
		}
		if (PersistentMap.class.isAssignableFrom(object.getClass())) {
			mapSerializer.writeObject(new HashMap(), out);
		} else {
			collectionSeiralizer.writeObject(new ArrayList(), out);
		}

	}
	
	@SuppressWarnings("unchecked")
	public static List convertListFromPersistentList(PersistentList plist) {
		List list = new ArrayList();
		if (plist != null) {
			for (int i = 0; i < plist.size(); i++) {
				list.add(plist.get(i));
			}
		}
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public static Set convertSetFromPersistentSet(PersistentSet pset){
		Set set = new HashSet();
		if (pset != null) {
			for (int i = 0; i < pset.size(); i++) {
				set.add(pset.toArray()[i]);
			}
		}
		return set;
	}
	
	public static Object convertPersistent(Object obj){
		 
		if(obj.getClass().isAssignableFrom(PersistentSet.class)){
			return convertSetFromPersistentSet((PersistentSet)obj);
		}else if (obj.getClass().isAssignableFrom(PersistentList.class)){
			return convertListFromPersistentList((PersistentList)obj);
		}else{
			return obj;
		}
	}
}

class LazySerializerForHibernate4 extends JavaSerializer {

	public LazySerializerForHibernate4(Class cls) {
		super(cls);
	}
	
	CollectionSerializer collectionSeiralizer = new CollectionSerializer();

	MapSerializer mapSerializer = new MapSerializer();

	/**
	 * @Title: writeObject
	 * @Description: TODO(override hessian write)
	 * @param @param object
	 * @param @param out
	 * @param @throws IOException
	 * @return void
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void writeObject(Object object, AbstractHessianOutput out)
			throws IOException {

		boolean ifHaveInit = Hibernate.isInitialized(object);

		if (ifHaveInit) {
			out.writeObject(object);
			out.flush();
			return;
		}

		try {
			if (Class
					.forName("org.hibernate.collection.internal.PersistentMap")
					.isAssignableFrom(object.getClass())) {
				mapSerializer.writeObject(new HashMap(), out);
			} else {
				collectionSeiralizer.writeObject(new ArrayList(), out);
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

###3. web.xml 中添加

<filter>
	<filter-name>osivFilter</filter-name>
	<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
    <!-- Hessian -->
    <!-- 解决 Hibernate session 在Hessian客户端序列化对象前提前关闭问题 -->
<filter-mapping>
	<filter-name>osivFilter</filter-name>
	<url-pattern>/remoting/*</url-pattern>
</filter-mapping>
    
    <!-- Hessian -->
<servlet>
    <servlet-name>hessian</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/config/application-context.xml
			,/WEB-INF/config/remoting-servlet.xml
		</param-value>
	</init-param>
</servlet>
<servlet-mapping>
    <servlet-name>hessian</servlet-name>
    <url-pattern>/remoting/*</url-pattern>
</servlet-mapping>

客户端:

###1. HessianClient.java

<!-- lang: java -->
import com.caucho.hessian.client.HessianProxyFactory;
import service.UnifiedUserMng;

public class HessianClient {
	
	public static void main(String[] args) throws Exception {
		// 远程调用地址
		String url = "http://localhost:8080/remoting/UnifiedUserService";
		// 默认写法
		HessianProxyFactory factory = new HessianProxyFactory(); // 实例化
		UnifiedUserService base = (UnifiedUserService) factory.create(UnifiedUserMng.class, url);
		// 调用接口,并打印结果
		System.out.println(base.getByUsername("admin").getEmail());
	}
}

总结

Hibernate抛出no session or session closed原因:Hessian调用服务器服务,序列化Hibernate持久化对象中集合对象(Set)时,session已经关闭。参考

© 著作权归作者所有

共有 人打赏支持
dexterman
粉丝 5
博文 32
码字总数 11697
作品 0
广州
程序员
Hibernate4.3+Spring4.2 整合问题

其实Spring+Hibernate的整合非常简单,只需要配置一个xml文件就可以将spring+hibernate整合起来。下面就以为一个添加用户的例子来整合这个: 首先实体必不可少的: 然后是实体对应的hbm文件(...

Mr_K
2016/07/12
150
2
SpringMVC整合Hessian

SpringMVC整合HessianSpring整合Hessian的demo网上一堆,适用于Srping+Struts2+Mybatis。但是SpirngMVC整合Hessina的也是很常见的,毕竟SpringMVC已经慢慢代替了Struts2。那么问题来了,因为...

大山_
2016/11/08
46
0
spring整合hibernate(注解、xml)applicationContext.xml配置

每次ssh框架整合都很麻烦,今天有空余时间总结下(主要总结spring+hibernate): 1.注解方式整合: applicationContext.xml配置文件: <?xml version="1.0" encoding="UTF-8"?><beans xmlns...

18号
2013/04/12
0
0
spring怎么对session进行管理,控制关闭

用spring+hibernate整合,,,在dao层查询了某个对象后,,,到service层后 想拿到关联对象里面的其他值,,,,但是取值的时候 报session已经关闭,,怎么控制session的关闭...

alone:
2012/02/21
2.7K
8
浅谈Hessian远程调用及其使用

1.1 概述 Hessian是一个轻量级的remoting onhttp工具,是由 caucho 提供的一种开源的远程通讯协议。相比WebService,Hessian更简单、快捷、同时支持跨语言通讯。Hessian采用的是二进制RPC协议...

科比可比克
2016/06/29
67
1

没有更多内容

加载失败,请刷新页面

加载更多

web打印控件 LODOP的详细api

web打印控件 LODOP的详细api

wangxujun59
23分钟前
1
0
从一次小哥哥与小姐姐的转账开始, 浅谈分布式事务从理论到实践

分布式事务是个业界难题,在看分布式事务方案之前,先从单机数据库事务开始看起。 什么是事务 事务(Transaction)是数据库系统中一系列操作的一个逻辑单元,所有操作要么全部成功要么全部失...

中间件小哥
25分钟前
5
0
荣登Github日榜!微信最新开源MMKV

MMKV 开源当日即登Github Trending日榜,三日后荣登周榜。MMKV 在腾讯内部开源半年,得到公司内部团队的广泛应用和一致好评。 MMKV 是基于 mmap 内存映射的移动端通用 key-value 组件,底层序...

腾讯开源
35分钟前
2
0
前端取色工具:jcpicker

http://annystudio.com/software/colorpicker/#jcp-download

轻量级赤影
37分钟前
1
0
Swift - 将图片保存到相册

import Photos func loadImage(image:UIImage) { UIImageWriteToSavedPhotosAlbum(image, self, #selector(saveImage(image:didFinishSavingWithError:contextInfo:)), ni......

west_zll
43分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部