springboot 使用hibernate进行双向关联json解析时死循环处理

一.问题

当我们进行hibernate进行双向关联时,我们用json解析时进入死循环,如果我们不用json不会死循环因为不用JSON时一般有懒加载不会出现死循环。
例如下面:
Examination.java中Examination一对多questions


    @OneToMany(targetEntity = Question.class, cascade = CascadeType.REMOVE, mappedBy = "examination", fetch = FetchType.LAZY)
    @OrderBy("id")
    private Set questions = new HashSet<>();

Question.java中Question多对一examination


    @ManyToOne(targetEntity = Examination.class, fetch = FetchType.LAZY)
    @JoinColumn(name = "examination_id", referencedColumnName = "id", nullable = false)
    private Examination examination;

二.方法

在类的开始或者属性的前面加上@JsonIgnoreProperties注解代码如下:

Entity
@Table(name = "examination", catalog = "questionnaire")
@JsonIgnoreProperties(value = {"user", "hibernateLazyInitializer", "hibernateLazyInitializer", "handler", "fieldHandler"})
public class Examination extends BaseBean {
    private static final long serialVersionUID = -2594676432596634203L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    //自测还是他测 self自测 other他测
    private String type;
    @Column(unique = true, nullable = false)
    private String name;
    //总共的时间
    private Integer allTime;

    public Double totalScore;
    @OneToMany(targetEntity = ExaminationComment.class, cascade = CascadeType.REMOVE, mappedBy = "examination", fetch = FetchType.EAGER)
    @OrderBy("subsection")
    private Set examinationComments = new HashSet<>();

    @OneToMany(targetEntity = Question.class, cascade = CascadeType.REMOVE, mappedBy = "examination", fetch = FetchType.LAZY)
    @OrderBy("id")
    private Set questions = new HashSet<>();

    @ManyToOne(targetEntity = User.class, fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id", referencedColumnName = "id", nullable = false)
    private User user;
@Entity
@Table(name = "question", catalog = "questionnaire")
@JsonIgnoreProperties(value = {"examination"})
public class Question extends BaseBean {

    private static final long serialVersionUID = 8720345728105271415L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    //文本内容
    private String title;
    //分数
    private Double score;

    private String content;
    //正确答案
    private String correctOption;

    private String comment;

    @ManyToOne(targetEntity = Examination.class, fetch = FetchType.LAZY)
    @JoinColumn(name = "examination_id", referencedColumnName = "id", nullable = false)
    private Examination examination;

    private String questionType;

    @OneToMany(targetEntity = ChoiceAnswer.class, fetch = FetchType.LAZY, mappedBy = "question", cascade = CascadeType.REMOVE)
    @OrderBy("theOption")
    private Set choiceAnswers = new HashSet<>();

你可能感兴趣的:(hibernate,springboot,spring的使用)