当将对象序列化为JSON响应时,避免Hibernate懒加载异常的更好方法

4

这是关于我一个月前提出的问题的参考

在这个问题中,避免json序列化时引发的懒加载异常的答案是将引起懒加载异常的变量设置为null。但是考虑到类具有许多依赖项,现在代码库已经增长,每次我都必须在代码的各个地方设置麻烦的变量以避免json序列化问题。当代码库很大时,这种方法看起来不太整洁。

下面是一个示例代码,它看起来不好。

//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);

你能否提出一种更好的方式来处理这个问题。谢谢。

1个回答

3
你可以使用@JsonIgnore注释来标记懒加载属性,这样在序列化时Jackson将忽略它。

非常感谢您的快速回复。有一个问题,反序列化时它是否也会忽略该字段? - lahiru madhumal
似乎是这样,http://jackson.codehaus.org/1.0.0/javadoc/org/codehaus/jackson/annotate/JsonIgnore.html,我还没有尝试过。 - Subin Sebastian
1
从json 1.9版本开始,setter和getter方法都被忽略了。如果只需要忽略序列化,则需要在getter方法中使用JsonIgnore注释,并且还需要添加JsonProperty注释到字段或setter方法中,以避免忽略反序列化等情况。感谢Subin的帮助!!! - lahiru madhumal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接