序列化为json响应时避免出现休眠惰性初始化异常的更好方法 [英] A better way to avoid hibernate lazy init exception when serializing in to a json response

查看:121
本文介绍了序列化为json响应时避免出现休眠惰性初始化异常的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是参考回答一个月前我问过的问题。 p>

在这个问题答案避免在json序列化时将惰性初始化异常设置为引起惰性初始化异常的变量的空值。但是考虑一下这个类何时有很多依赖关系。现在随着代码库的增多,每次我必须将代码中的麻烦变量设置为null以避免json序列化问题。当代码基数很大时,该方法看起来并不整齐。



下面显示的示例代码看起来不太好。

  //设置一些变量以避免jackson mapper序列化中的延迟init异常
batch.setEnrollmentList(null);
列表< BatchSchedule> scheduleList =(ArrayList< BatchSchedule>)batch.getBatchScheduleList(); (BatchSchedule batchSchedule:scheduleList){
batchSchedule.setBatch(null);


}
batch.getLecturer()。setBatchList(null);
batch.getLecturer()。setSubjectList(null);
batch.getSubject()。setBatchList(null);
batch.getSubject()。setLecturerList(null);

您能否给我一个更好的方法来解决这个问题。
Thanks。

解决方案

您可以使用 @JsonIgnore ,以便Jackson在序列化时忽略它。


This is in reference to a question I asked a month back.

In this question the answer to avoid the lazy init exception when json serializing was to set null to the variables that cause lazy init exception. But consider when the class has many dependencies. Now with the code base is grown and every time I have to set null to the troublesome variables everywhere in the code to avoid json serializing problem. The method does not look neat when the code base is large.

An example code is shown below that doesn't look good.

//setting some variables to avoid lazy init exception in jackson mapper serialization
batch.setEnrollmentList(null);
List<BatchSchedule> scheduleList = (ArrayList<BatchSchedule>) batch.getBatchScheduleList();

            for (BatchSchedule batchSchedule : scheduleList) {
                batchSchedule.setBatch(null);
            }
            batch.getLecturer().setBatchList(null);
            batch.getLecturer().setSubjectList(null);
            batch.getSubject().setBatchList(null);
            batch.getSubject().setLecturerList(null);

Can you please suggest me a better way to handle this problem. Thanks.

解决方案

You can annotate the lazy properties with @JsonIgnore so that Jackson ignores it while serializing.

这篇关于序列化为json响应时避免出现休眠惰性初始化异常的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆