首页 > 解决方案 > org.hibernate.LazyInitializationException after using HibernateProxyTypeAdapter for Gson

问题描述

I was having an issue with Gson because it can't pass to Json HibernateProxy objects, so I have followed this guide: link

This solve the typeAdapter problem with Gson, but now I'm getting the following exception:

org.hibernate.LazyInitializationException: could not initialize proxy - no Session

I have been searching how to solve this but the solutions that I have found don't work in this case.

This is my code:

List<ContratoSolicitudFull> returnValue = 
                    new SomeBL().getData(id, null, null,currentUserId);

Type type = new TypeToken<List<ContratoSolicitudFull>>() {}.getType();
    Gson gson = new GsonBuilder()
            .registerTypeAdapter(DateTime.class, new DateTimeJsonConverter())
            .registerTypeAdapter(LocalDate.class, new LocalDateJsonConverter())
            .registerTypeAdapterFactory(HibernateProxyTypeAdapter.FACTORY)
            .create();
    String jsonValue = gson.toJson(returnValue, type); //Here is where it fail

Any idea?

标签: javahibernategson

解决方案


通过序列化为 json,您可以在会话上下文之外访问未获取的数据。

如果您使用的代码与链接中的代码完全相同,请尝试将 write 方法更改为此。

@SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    public void write(JsonWriter out, HibernateProxy value) throws IOException {
        //avoid serializing non initialized proxies
        if (value == null || !Hibernate.isInitialized(value)) {
            out.nullValue();
            return;
        }
        // Retrieve the original (not proxy) class
        Class<?> baseType = Hibernate.getClass(value);
        // Get the TypeAdapter of the original class, to delegate the serialization
        TypeAdapter delegate = context.getAdapter(TypeToken.get(baseType));
        // Get a filled instance of the original class
        Object unproxiedValue = ((HibernateProxy) value).getHibernateLazyInitializer()
                .getImplementation();
        // Serialize the value
        delegate.write(out, unproxiedValue);
    } 

|| !Hibernate.isInitialized(value)添加以检查集合是否已初始化,如果没有则避免访问它。


推荐阅读