fastjson序列化hibernate代理和延迟加载对象出现no session异常的解决办法

前端之家收集整理的这篇文章主要介绍了fastjson序列化hibernate代理和延迟加载对象出现no session异常的解决办法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

fastjson序列化hibernate代理和延迟加载对象出现org.hibernate.LazyInitializationException: Failed to lazily initialize a collection of role: com.eecn.warehouse.api.model.Tags.childTags,could not initialize proxy - no Session。

对于这个可以使用fastjson给出的扩展点,实现PropertyFilter接口,过滤不想序列化的属性

下面的实现,如果是hibernate代理对象或者延迟加载的对象,则过滤掉,不序列化。如果有值,就序列化。

  1. package com.test.json;
  2.  
  3. import org.hibernate.collection.spi.PersistentCollection;
  4. import org.hibernate.proxy.HibernateProxy;
  5. import org.hibernate.proxy.LazyInitializer;
  6.  
  7. import com.alibaba.fastjson.serializer.PropertyFilter;
  8.  
  9. public class SimplePropertyFilter implements PropertyFilter {
  10.  
  11. /**
  12. * 过滤不需要被序列化的属性,主要是应用于Hibernate的代理和管理。
  13. * @param object 属性所在的对象
  14. * @param name 属性
  15. * @param value 属性
  16. * @return 返回false属性将被忽略,ture属性将被保留
  17. */
  18. @Override
  19. public boolean apply(Object object,String name,Object value) {
  20. if (value instanceof HibernateProxy) {//hibernate代理对象
  21. LazyInitializer initializer = ((HibernateProxy) value).getHibernateLazyInitializer();
  22. if (initializer.isUninitialized()) {
  23. return false;
  24. }
  25. } else if (value instanceof PersistentCollection) {//实体关联集合一对多等
  26. PersistentCollection collection = (PersistentCollection) value;
  27. if (!collection.wasInitialized()) {
  28. return false;
  29. }
  30. Object val = collection.getValue();
  31. if (val == null) {
  32. return false;
  33. }
  34. }
  35. return true;
  36. }
  37.  
  38. }
当然,可以上述类,继续进行扩展,添加构造函数,配置,指定Class,以及该Class的哪个属性需要过滤。进行更精细化的控制。后面再续。

调用的时候,使用如下的方式即可,声明一个SimplePropertyFilter

  1. @RequestMapping("/json")
  2. public void test(HttpServletRequest request,HttpServletResponse response) {
  3. Tags tags = tagsDaoImpl.get(2);
  4. Tags parentTags = tagsDaoImpl.get(1);
  5. tags.setParentTags(parentTags);
  6. long d = System.nanoTime();
  7. SimplePropertyFilter filter = new SimplePropertyFilter();
  8. String json = JSON.toJSONString(tags,filter);
  9. System.out.println(System.nanoTime() -d);
  10. ObjectMapper mapper = new ObjectMapper();
  11. mapper.registerModule(new Hibernate4Module());
  12. mapper.setSerializationInclusion(Include.NON_NULL);
  13. long d2 = System.nanoTime();
  14. String json2 = null;
  15. try {
  16. json2 = mapper.writeValueAsString(tags);
  17. } catch (JsonProcessingException e) {
  18. }
  19. System.out.println(System.nanoTime() - d2);
  20. System.out.println(json);
  21. System.out.println(json2);
  22. }

上面的代码同样展示了,如果使用jackson,这里使用的是jackson2,想序列化hibernate代理和延迟加载的对象,你需要引入hibernate4module。Maven以来如下
  1. <dependency>
  2. <groupId>com.fasterxml.jackson.datatype</groupId>
  3. <artifactId>jackson-datatype-hibernate4</artifactId>
  4. <version>2.2.3</version>
  5. </dependency>
绝对原创,保留一切权利。转载请注明出处。

猜你在找的Json相关文章