java 解决实体类序列化时,报failed to lazily initialize 的问题

阅读更多

java 解决实体类序列化时,报failed to lazily initialize 的问题

具体报错信息:

org.codehaus.jackson.map.JsonMappingException: failed to lazily initialize a collection of role: com.girltest.entity.Test2Boy.conventions, could not initialize proxy - no Session (through reference chain: java.util.HashMap["recordList"]->java.util.ArrayList[0]->com.girltest.entity.Test2Boy["conventions"])

原因:因为实体类中有hibernate懒加载的成员变量

解决方法:

json序列化之前 ,把懒加载的成员变量设置为null

/***
	 * get all field ,including fields in father/super class
	 * 
	 * @param clazz
	 * @return
	 */
	public static List getAllFieldList(Class clazz) {
		if (clazz == null) {
			return null;
		}
		List fieldsList = new ArrayList();// return object
		Class superClass = clazz.getSuperclass();// father class
		if(ValueWidget.isNullOrEmpty(superClass)){
			return null;
		}
		if (!superClass.getName().equals(Object.class.getName()))/*
																 * java.lang.Object
																 */{

			// System.out.println("has father");
			fieldsList.addAll(getAllFieldList(superClass));// Recursive
		}
		Field[] fields = clazz.getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			Field field = fields[i];
			// 排除因实现Serializable 接口而产生的属性serialVersionUID
			if (!field.getName().equals("serialVersionUID")) {
				fieldsList.add(field);
			}
		}
		return fieldsList;
	}


 /***
     * 过滤hibernate懒加载的成员变量
* org.codehaus.jackson.map.JsonMappingException: failed to lazily initialize a collection of role: com.girltest.entity.Test2Boy.conventions, could not initialize proxy - no Session (through reference chain: java.util.HashMap["recordList"]->java.util.ArrayList[0]->com.girltest.entity.Test2Boy["conventions"]) * * @param obj * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */ public static void skipHibernatePersistentBag(Object obj) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { if (obj == null) { return; } List fieldsList = getAllFieldList(obj.getClass()); if (ValueWidget.isNullOrEmpty(fieldsList)) { return; } for (int i = 0; i < fieldsList.size(); i++) { Field f = fieldsList.get(i); Object vObj = getObjectValue(obj, f); if (null != vObj && vObj.getClass().getName().equals("org.hibernate.collection.internal.PersistentBag")) { f.setAccessible(true); f.set(obj, null); } } } try { ReflectHWUtils.skipHibernatePersistentBag(object); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); }

 

 

你可能感兴趣的:(hibernate,hibernate,lazy,load)