fastjson序列化hibernate代理和延遲載入物件出現no session異常的解決辦法
阿新 • • 發佈:2019-02-01
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代理物件或者延遲載入的物件,則過濾掉,不序列化。如果有值,就序列化。
當然,可以上述類,繼續進行擴充套件,新增建構函式,配置,指定Class,以及該Class的哪個屬性需要過濾。進行更精細化的控制。後面再續。package com.test.json; import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.LazyInitializer; import com.alibaba.fastjson.serializer.PropertyFilter; public class SimplePropertyFilter implements PropertyFilter { /** * 過濾不需要被序列化的屬性,主要是應用於Hibernate的代理和管理。 * @param object 屬性所在的物件 * @param name 屬性名 * @param value 屬性值 * @return 返回false屬性將被忽略,ture屬性將被保留 */ @Override public boolean apply(Object object, String name, Object value) { if (value instanceof HibernateProxy) {//hibernate代理物件 LazyInitializer initializer = ((HibernateProxy) value).getHibernateLazyInitializer(); if (initializer.isUninitialized()) { return false; } } else if (value instanceof PersistentCollection) {//實體關聯集合一對多等 PersistentCollection collection = (PersistentCollection) value; if (!collection.wasInitialized()) { return false; } Object val = collection.getValue(); if (val == null) { return false; } } return true; } }
呼叫的時候,使用如下的方式即可,宣告一個SimplePropertyFilter
@RequestMapping("/json") public void test(HttpServletRequest request, HttpServletResponse response) { Tags tags = tagsDaoImpl.get(2); Tags parentTags = tagsDaoImpl.get(1); tags.setParentTags(parentTags); long d = System.nanoTime(); SimplePropertyFilter filter = new SimplePropertyFilter(); String json = JSON.toJSONString(tags, filter); System.out.println(System.nanoTime() -d); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new Hibernate4Module()); mapper.setSerializationInclusion(Include.NON_NULL); long d2 = System.nanoTime(); String json2 = null; try { json2 = mapper.writeValueAsString(tags); } catch (JsonProcessingException e) { } System.out.println(System.nanoTime() - d2); System.out.println(json); System.out.println(json2); }
上面的程式碼同樣展示了,如果使用jackson,這裡使用的是jackson2,想序列化hibernate代理和延遲載入的物件,你需要引入hibernate4module。Maven以來如下
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate4</artifactId>
<version>2.2.3</version>
</dependency>
絕對原創,保留一切權利。轉載請註明出處。