序列化到json响应时避免hibernate延迟初始化exception的更好方法

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

在这个问题中 ,当json序列化时避免延迟初始化exception的答案是将null设置为导致延迟初始化exception的变量。 但是考虑一下这个类有多少依赖关系。 现在随着代码库的增长而每次我都要将代码中的麻烦变量设置为null以避免json序列化问题。 当代码库很大时,该方法看起来不整洁。

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

//setting some variables to avoid lazy init exception in jackson mapper serialization batch.setEnrollmentList(null); List scheduleList = (ArrayList) 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); 

你能否告诉我一个更好的方法来处理这个问题。 谢谢。

您可以使用@JsonIgnore注释惰性属性,以便Jackson在序列化时忽略它。