Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy Loadng error in JSON serializer

I have such kind of @OneToOne Hibernate relationShip

public class Address implements Serializable {

    private String id;
    private String city;
    private String country;
//setter getters ommitted
}

public class Student implements Serializable {

    private String id;
    private String firstName;
    private String lastName;    
    private Address address;
}

address Item is mapped as LAZY.

Now I want to fetch user and it's address using

session.load(Student.class,id);

In my daoService.

Then I return it as JSON from my Spring MVC controller:

@RequestMapping(value="/getStudent.do",method=RequestMethod.POST)
    @ResponseBody
    public Student getStudent(@RequestParam("studentId") String id){
        Student student = daoService.getStudent(id);
        return student;
    }

Unfortunately, it's not working because of Lazy clasees and I fails with:

org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.vanilla.objects.Student_$$_javassist_1["address"]->com.vanilla.objects.Address_$$_javassist_0["handler"])
    at org.codehaus.jackson.map.ser.StdSerializerProvider$1.serialize(StdSerializerProvider.java:62)

I do use OpenSessionInViewInterceptor and it works just fine. I understand that I can user left join HQL query and retrieve student and address that way and solve the problem. I also understand that changing relation to EAGER will solve it.

But how can I serialize to JSON lazy classes using standard jackson message converter which of cause I added to my XML file.

like image 334
danny.lesnik Avatar asked Dec 07 '22 21:12

danny.lesnik


2 Answers

The easiest solution: Don't serialize entities, use Value Objects.

If that is not an option for you, make sure that the entity Object is detached.

With JPA (2), you would use EntityManager.detach(entity), with plain Hibernate the equivalent is Session.evict(entity).

like image 200
Sean Patrick Floyd Avatar answered Dec 19 '22 02:12

Sean Patrick Floyd


Once I write a processor to handle this but now it's easy to fix this by using the jackson hibernate module.

like image 36
NewBee Avatar answered Dec 19 '22 03:12

NewBee