代码之家  ›  专栏  ›  技术社区  ›  DMC19

使用HibernateProxyTypeAdapter for GSON后出现org.hibernate.lazyInitializationException异常

  •  0
  • DMC19  · 技术社区  · 7 年前

    我对gson有问题,因为它不能传递给json hibernateproxy对象,所以我遵循了以下指南: link

    这解决了gson的typeadapter问题,但现在我得到了以下异常:

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

    我一直在寻找如何解决这个问题,但我找到的解决方案在这种情况下不起作用。

    这是我的代码:

    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
    

    有什么想法吗?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Michal    7 年前

    通过序列化到json,您可以访问会话上下文之外的未蚀刻数据。

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

    @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) 已添加以检查集合是否已初始化,如果未初始化则避免访问它。