简体   繁体   中英

A better way to avoid hibernate lazy init exception when serializing in to a json response

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM