JSON序列化程序中的Lazy Loadng错误

dan*_*nik 4 spring json hibernate lazy-loading spring-mvc

我有这种@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;
}
Run Code Online (Sandbox Code Playgroud)

地址项目映射为LAZY.

现在我想使用获取用户及其地址

session.load(Student.class,id);
Run Code Online (Sandbox Code Playgroud)

在我的daoService中.

然后我从Spring MVC控制器返回JSON:

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

不幸的是,由于懒惰的clasees它没有工作,我失败了:

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)
Run Code Online (Sandbox Code Playgroud)

我确实使用OpenSessionInViewInterceptor,它工作得很好.我知道我可以使用左连接HQL查询并检索学生并解决这个问题并解决问题.我也明白,改变与EAGER的关系将解决它.

但是如何使用标准的jackson消息转换器序列化为JSON惰性类,这是因为我添加到了我的XML文件中.

Sea*_*oyd 6

最简单的解决方案:不要序列化实体,使用值对象.

如果这不是您的选项,请确保已分离实体Object.

使用JPA(2),你可以使用EntityManager.detach(entity)普通的Hibernate,相当于Session.evict(entity).


New*_*Bee 5

一旦我编写处理器来处理这个问题,但现在通过使用jackson hibernate模块很容易解决这个问题.