查询报错:java.lang.StackOverflowError: null

java.lang.StackOverflowError: null

字面理解报错的原因是栈溢出。

我这里仅讲由于使用JPA导致的java.lang.StackOverflowError: null

例子:

清洁工实体

@Data
@Entity
@Table(name = "cms_cleaner")
public class Cleaner implements Serializable {

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "cms_cleaner_room",
            joinColumns = {@JoinColumn(name = "CLEANER_ID", referencedColumnName = "cleanerId")},
            inverseJoinColumns = {@JoinColumn(name = "ROOM_ID", referencedColumnName = "roomId")})
    private Set rooms = new HashSet();
    
}

课室实体

@Entity
@Table(name="Room")
@Data
@DynamicUpdate
public class Room implements Serializable {

    @JsonIgnore
    @ManyToMany(mappedBy = "rooms", fetch = FetchType.EAGER, cascade = {CascadeType.MERGE, CascadeType.REFRESH})
    private Set cleaners=new HashSet();

}

原因:查询时产生了死循环或无限递归

输出一个room对象时,也会输出cleanerlist,因为是双向关联的,所以也会触发cleaner对象,接下来便是rooms。。。产生无限递归,导致栈溢出。

解决:

办法一

for(Room room : cleaner.getRoomList()){
      //提前终止,这样便不会产生无限递归
      room.setRoomList(null);
      System.out.println(role);

}

办法二

把双向的关联变为单向的关联。

即删除Room实体类中的:

 @JsonIgnore
    @ManyToMany(mappedBy = "rooms", fetch = FetchType.EAGER, cascade = {CascadeType.MERGE, CascadeType.REFRESH})
    private Set cleaners=new HashSet();

办法三

将两个实体类中的@ManyToMany均改成@OneToMany。

你可能感兴趣的:(Hibernate)