简体   繁体   中英

Spring MVC controller Json response, hibernate proxy error

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM