`

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<Field> getAllFieldList(Class<?> clazz) {
		if (clazz == null) {
			return null;
		}
		List<Field> fieldsList = new ArrayList<Field>();// 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懒加载的成员变量<br />
     * 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<Field> 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();
                }

 

 

1
1
分享到:
评论

相关推荐

    react-lazily-render:延迟安装昂贵的组件,直到将占位符组件滚动到视图中为止

    npm install --save react-lazily-render 用法 () import React from 'react' ; import LazilyRender from 'react-lazily-render' ; ...lots of content... &lt; LazilyRender xss=removed&gt; } content = { ...

    Git-2.21.0-64-bit.zip

    committed, the command line prompt script failed to notice the current status, which has been improved. * Many GIT_TEST_* environment variables control various aspects of how our tests are run, ...

    react-lazily-img:React Wrapper组件使用IntersectionObserver API延迟加载图像

    懒惰地ReactIMG React Lazily IMG是一个React Wrapper组件,用于延迟加载图像。 目标是使用方便且已知的标准HTML标记,并只是延迟加载它们。特征图片标签和IMG srcset支持Webp检测占位符HTML && CSS图像支持下载图像...

    JavaScript Concurrency pdf 无水印 0分

    Compute values lazily and avoid unnecessary memory allocations using generators Write concurrent code that doesn't feel like concurrent code by abstracting away boilerplate chores Leverage true ...

    Android代码-ixjava

    The aim is to provide, lazily evaluated, pull-based datastream support with the same naming as in RxJava mainly for the pre-Java-8 world. The Stream API in Java 8 is not exactly the same thing because...

    Pandas Cookbook 2017 pdf 2分

    Slicing rows lazily Getting ready How to do it... How it works... There's more... Slicing lexicographically Getting ready How to do it... How it works... There's more... 5. Boolean Indexing ...

    springframework.5.0.12.RELEASE

    Allow java.time types for setting the Last-Modified header [SPR-17571] #22103 StringHttpMessageConverter should assume charset UTF-8 for application/json [SPR-17568] #22100 NettyDataBufferFactory.join...

    Qazy:延迟加载 - 没有 SEO 负面影响

    -- data-qazy is set to true means to load it lazily. Set it to false if you don't want to load it lazily. --&gt; &lt;!-- A default placeholder is used. To change the placeholder, assign the variable ...

    arguments-call-apply.rar_Windows编程_Java_

    Try invoking call before sum has been compiled lazily.

    OSGI in Action

    9.3 Starting bundles lazily 314 Understanding activation policies 315 ■ Using activation policies 316 9.4 Summary 317 10 Managing applications 319 10.1 Deploying bundles 320 Introducing management ...

    Redis的Scala客户端Scredis.zip

    // Subscribes to a Pub/Sub channel using the internal, lazily initialized SubscriberClient redis.subscriber.subscribe("My Channel") {  case message @ PubSubMessage.Message(channel, ...

    Android代码-clojure-jsr223

    lazily. Copyright (c) 2009 Armando Blancas. All rights reserved. The use and distribution terms for this software are covered by the Eclipse Public License 1.0 ...

    Android代码-Kodein-DI

    Lazily instantiate your dependencies when needed Stop caring about dependency initialization order Easily bind classes or interfaces to their instance or provider Easily debug your dependency bindings...

    cinnamon:一个简单的部署工具

    名称 Cinnamon-简约的部署工具 概要 use strict; use warnings; # Exports some commands use Cinnamon::DSL; my $application = 'My::App';...# Lazily evaluated if passed as a code set lazy_value =&gt; sub { #.

    Python Cookbook英文版

    8.11 Establishing Database Connections Lazily 8.12 Accessing a JDBC Database from a Jython Servlet 8.13 Module: jet2sql-Creating a SQL DDL from an Access Database 9. User Interfaces 9.1 ...

    svc.rar_Will

    Will be lazily created when running layout tests.namespace content.

    Android组件ViewStub基本使用方法详解

    “A ViewStub is an invisible, zero-sized View that can be used to lazily inflate layout resources at runtime. When a ViewStub is made visible, or when inflate() is invoked, the layout resource is ...

    get-all-files::high_voltage:具有懒惰同步和异步迭代器支持的快速递归目录搜寻器

    获取所有文件 具有延迟同步和异步...// Lazily iterate over filenames synchronously for ( const filename of getAllFiles . sync ( &#96;path/to/dir/or/file` ) ) { // Could break early on some condition a

    Free Hex Control

    / specific area difficult, so I lazily redraw almost the whole control whenever / it needs. This results in the slowness (I suggest you can use the control in data / display, ^_^). In next version,...

    stream.js Javascript

    stream.js 是一个很小、完全独立的Javascript类库,它为你提供了一个新的...他的这种魔力来自于具有延后(lazily)执行的能力。这简单的术语完全能表明它们可以加载无穷多的元素。(http://www.aqee.net/docs/stream/)

Global site tag (gtag.js) - Google Analytics