在使用spring data jpa 的过程中,有时候会有双向依赖的需求,如查询班级时需要级联查出班级内所有的学生,查询学生时需要查询学生所在的班级。体现在代码中便是
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15public class ClassOne implements Serializable{ private static final long serialVersionUID = -15535318388014800L; private Long id; private String className; @OneToMany(mappedBy = "class", fetch = FetchType.LAZY) private Set<Student> students; } public class Student implements Serializable{ private static final long serialVersionUID = -15535318388014800L; private Long id; private String studentName; @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "class_id") private ClassOne class; }
这种情况在查询序列化的过程中,一端加载多端,多端有依赖一段,就会造成死循环的现象出现。解决这个问题通常由三种方法。
1. 使用DTO对象,查询出信息后使用DTO对象进行封装,最后传给前台,在序列化之前将依赖关系去除掉。
2.使用@JsonIgnore注解,在关联对象上添加这个注解,使在序列化是忽略掉这个字段。但是同时关联的对象也不会在josn数据中出现。
3.@JsonIgnoreProperties注解,这个注解可以选择性的忽略固定字段,也就是说可以在查询班级的时候,忽略掉班级所级联出来的学生的班级字段,从而避免死循环。这个方法技能解决死循环,又能将级联到的数据返回到json。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class ClassOne implements Serializable{ private static final long serialVersionUID = -15535318388014800L; private Long id; private String className; @JsonIgnoreProperties({"class"}) @OneToMany(mappedBy = "class", fetch = FetchType.LAZY) private Set<Student> students; } public class Student implements Serializable{ private static final long serialVersionUID = -15535318388014800L; private Long id; private String studentName; @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "class_id") @JsonIgnoreProperties({"students"}) private ClassOne class; }
最后
以上就是靓丽八宝粥最近收集整理的关于解决spring data jpa 双向依赖死循环问题的全部内容,更多相关解决spring内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复