0

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?

DMC19
  • 825
  • 2
  • 14
  • 33

1 Answers1

2

By serialization to json, you are accessing unfetched data outside of a session context.

If you used exactly the same code as in your link then, try to change write method to 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) was added to check if collection was initialized, and if not avoids accessing it.

Michal
  • 970
  • 7
  • 11