0

I have a Spring controller annotated class which implements this method:

  @RequestMapping(value = "/event/eventList", method = RequestMethod.GET)
    public @ResponseBody List<Event> listEvents() {
        System.out.println("############ LIST EVENTS ############");
        List<Event> events = eventService.listAllEvents();
        for(Event event : events) {
            Hibernate.getClass(event);
            System.out.println(event);
        }
        return events;
    }

when I call the page (localhost:8080/myapp/event/eventList) from browser, the method will be called correctly i see all the logs and the events are printed correctly meaning the event list is not empty and valid, but I get the error:

GRAVE: Servlet.service() for servlet [dispatcher] in context with path [/myapp] threw exception [Request processing failed; nested exception is java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?] with root cause
java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?

It does not return any Json representation. I changed the method to return a string like:

@RequestMapping(value = "/event/eventList", method = RequestMethod.GET)
public @ResponseBody String listEvents() {

    return "{'pippo':1}";
}

In this case the browser show the string correctly.

did I miss something?

mattobob
  • 717
  • 2
  • 12
  • 31
  • 2
    It tells you right there, it cannot serialize a HibernateProxy. `Hibernate.getClass` doesn't make the proxy object go magically away. You need to "unpack" it, something like `.getHibernateLazyInitializer().getImplementation()` could do it, or just fix your architecture and don't give the controller Entities but DTOs. – dav1d Dec 17 '16 at 19:46

1 Answers1

1

The exception is thrown by com.google.gson.internal.bind.TypeAdapters when GSON is trying to serialize variable 'events' to Json.

This happens, cause

eventService.listAllEvents() 

returns not a list already containing all events, but hibernate proxy that will do that lazy, when the list is actually used. GSON does not know how to serialize that proxy.

Hibernate.getClass should initialize the underlying object as a side effect.

You need to call it also for the List 'events' itself, not only for every single event. The List can be a hibernate proxy also.

You may find more info on that topic at Could not serialize object cause of HibernateProxy

Community
  • 1
  • 1
  • Thanks Stefan, the solution for me was to add Annotation `@JsonIgnore` on every class variable in Event representing an external relationship. – mattobob Dec 28 '16 at 09:00