XStream with hibernate 解决Cannot handle CGLIB enhan

在hibernate下使用XStream会有Cannot handle CGLIB enhanced proxies with multiple callbacks的问题,原因在于hibernate取出来的集合对象其实不是POJO的集合,而是依赖于HIBERNATE API的代理对象,在网上找了下,找到这篇文章
先做记录,有时间做下翻译

以下的代码只在hibernate 2下面做了测试,但是理论上同样适用于hibernate 3

解决这个问题的关键在于,让JVM像处理java.util包下面的 Collection一样处理hibernate的Collection,这样就可以避免臭名昭著"com.thoughtworks.xstream.converters.ConversionException: Cannot handle CGLIB enhanced proxies with multiple callbacks..."异常。

主要分为三个步骤,首先,告诉Xstream像处理java Collection一样处理hibernate Collection

xstream.addDefaultImplementation(
        net.sf.hibernate.collection.List.class, java.util.List.class);
xstream.addDefaultImplementation(
        net.sf.hibernate.collection.Map.class, java.util.Map.class);
xstream.addDefaultImplementation(
        net.sf.hibernate.collection.Set.class, java.util.Set.class);


然后需要注册一些Coverter来帮助Xstream处理这些hibernaye Collection
Mapper mapper = xstream.getMapper();
xstream.registerConverter(new HibernateCollectionConverter(mapper));
xstream.registerConverter(new HibernateMapConverter(mapper));


这样,这些转换器就加入到了Xstream内建的转换器队列当中。在完成了具体的转换代码之后,Xstream就具备了处理hibernate Collection的能力

import net.sf.hibernate.collection.List;
import net.sf.hibernate.collection.Set;
import com.thoughtworks.xstream.converters.collections.CollectionConverter;
import com.thoughtworks.xstream.mapper.Mapper;

class HibernateCollectionConverter extends CollectionConverter {
    HibernateCollectionConverter(Mapper mapper) {
        super(mapper);
    }

    public boolean canConvert(Class type) {
        return super.canConvert(type) || type == List.class || type == Set.class; 
    }
}

and
import net.sf.hibernate.collection.Map;
import com.thoughtworks.xstream.converters.collections.MapConverter;
import com.thoughtworks.xstream.mapper.Mapper;

class HibernateMapConverter extends MapConverter {

    HibernateMapConverter(Mapper mapper) {
        super(mapper);
    }

    public boolean canConvert(Class type) {
        return super.canConvert(type) || type == Map.class; 
    }
}



这些就是全部了,基本可以解决Hibernate + Xstream出现的问题,Good Luck!

你可能感兴趣的:(java,jvm,.net,Hibernate)