java开发中,经常需要将父子对象的数据,通过json方式输出到前台,但使用json-lib输出时往往会出现,级联循环造成java的堆栈溢出,所以其对应的解决方案也很简单,就是破除级联。
例子如下:
public class Grain implements java.io.Serializable {
.....
private Set<GrainPic> grainPics = new HashSet<GrainPic>(0); //储粮图片
.....
@OneToMany(fetch = FetchType.LAZY, mappedBy = "TGrain", cascade = {CascadeType.ALL })
public Set<GrainPic> getGrainPics() {
return this.grainPics;
}
public void setGrainPics(Set<GrainPic> grainPics) {
this.grainPics = grainPics;
}
}
@Entity
@Table(name = "t_grain_pic")
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler",
"tgrain" // 此处最关键,即不再回转输出Grain对象
}) //破除子对象往回级联输出
public class GrainPic implements java.io.Serializable {
private int id;
private Grain TGrain;
private String pic;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PID")
public Grain getTGrain() {
return this.TGrain;
}
public void setTGrain(Grain TGrain) {
this.TGrain = TGrain;
}
@Column(name = "pic", nullable = false)
public String getPic() {
return this.pic;
}
public void setPic(String pic) {
this.pic = pic;
}
}
上面的例子中 :Grain对象中通过grainPics 属性级联子对象GrainPic ,而GrainPic 对象又通过TGrain属性关联Grain对象,那么在json输出时就回形成一个这样的无限循环而内存溢出:
Grain->GrainPic->Grain->GrainPic .....
所以,最好的解决办法就是破除这个环,即在Grain->GrainPic 后不再循环输出Grain,问题得到圆满解决。