@Entity
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private Timestamp date;
private String room;
@OneToOne(cascade=CascadeType.ALL)
private People people;
@ManyToMany(cascade=CascadeType.ALL)
private Set<Teacher> teachers = new HashSet<>();
}
当我使用hql查询全部Student时,出现该错误java.lang.StackOverflowError,后来发现时在student类中重写的tostring方法中包含有其他的对象,而在所包含的对象中又包含有对象,所以内存不停的在存储对象,最后导致栈溢出。
@Override
public String toString() {
return "Student [id=" + id + ", date=" + date + ", room=" + room
+ ", people=" + people + ", teachers=" + teachers + "]";
}
但是如果tostring所包含的对象的tostring方法中只包含有基本数据类型,则不会发生栈溢出。eg:Student类的toString方法中包含有people,但是people类中值包含基本数据类型。