JPA一对多、多对多json序列化死循环问题解决

Task

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * Created by change.
 * 任务
 */
@Entity
@Table(name = "task")
@Data
public class TaskEntity implements Serializable {

    private static final long serialVersionUID = -8305163456196952851L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String target;

    @Column
    private int type;

    @Column(name = "start_at")
    private Date startAt;

    @Column(name = "end_at")
    private Date endAt;

    @Column(name = "data_path")
    private String dataPath;

    @Column
    private int status;

    @Column(name = "status_text")
    private String statusText;

    @Column
    private String description;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "taskEntity")
    private List searchPoliceEntityList;

}

SearchPolice

import com.fasterxml.jackson.annotation.JsonBackReference;

import javax.persistence.*;
import java.io.Serializable;

/**
 * Created by challenge.
 * 搜索策略
 */
@Entity
@Table(name = "search_police")
@Data
public class SearchPoliceEntity implements Serializable {

    private static final long serialVersionUID = -2766200716493656577L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private int rate;

    @Column
    private String level;

    @Column(name = "snr")
    private String SNR;

    @ManyToOne
    @JoinColumn(name = "task_id")
    @JsonBackReference
    private TaskEntity taskEntity;
}

json序列化的对象中存在双向引用会导致的无限递归(infinite recursion)问题。
使用@JsonBackReference标记在有多对一或者多对多关系的属性上即可解决这个问题。

ps:
@JsonManagedReference:标记的属性会被序列化,序列化时属性默认都是会被序列化的。反序列(deserialization,即json数据转换为对象)时,如果没有@JsonManagedReference,则不会自动注入@JsonBackReference标注的属性。
@JsonIgnore:直接忽略某个属性,以断开无限递归,序列化或反序列化均忽略。当然如果标注在get、set方法中,则可以分开控制,序列化对应的是get方法,反序列化对应的是set方法。在父子关系中,当反序列化时,@JsonIgnore不会自动注入被忽略的属性值(父或子),这是它跟@JsonBackReference和@JsonManagedReference最大的区别。

你可能感兴趣的:(JPA一对多、多对多json序列化死循环问题解决)