JPA中一对多双向关联堆栈溢出问题

本人小白,
在使用了一对多和多对一的时候出了点问题,具体关联方式如下:

  • SysUser
@Entity
@Data
@GenericGenerator(name = "jpa-uuid", strategy = "uuid")
public class SysUser implements Serializable {
    @Id
    @GeneratedValue(generator = "jpa-uuid")
    private String id;
    private String email;
    private String password;
    private String avatar;
    private String nickname;
    private Long focus;
    private Long fans;
    private Long articleCount;
    private Long fontCount;
    private Long likes;

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "articleAuthor")
    private List
userArticles; }
  • Article
@Entity
@Data
@GenericGenerator(name = "jpa-uuid", strategy = "uuid")
public class Article implements Serializable {
    @Id
    @GeneratedValue(generator = "jpa-uuid")
    private String id;

    private String title;
    private String synopsis;
    private String cover;
    private String content;
    private Long wordCounts;
    private Long readCounts;
    private Long comments;
    private Long loves;
    private String creationTime;

    @ManyToOne(cascade={CascadeType.MERGE,CascadeType.REFRESH})
    @JoinColumn(name = "author_id")
    private SysUser articleAuthor;

}

当使用SysUser类去关联查询的时候,会这样一个错误
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.soft1611.jianshu.domain.entity.SysUser.userArticles, could not initialize proxy - no Session
这里的意思是一方这边是惰性加载,在查找之前session已经关闭,所以无法查找到关联的数据,因此而报错。


那我们将一方的加载方式改为fetch = FetchType.EAGER再运行项目,结果又出问题,错误是:java.lang.StackOverflowError堆栈溢出错误


在网上查找了很多,这里总结了点方法:

  • 破坏某一方的toString方法,不要让他打印被定义方的数据;

你可能感兴趣的:(JPA中一对多双向关联堆栈溢出问题)