SpringJpa中ManyToMany、ManyToOne導致的死循環(java.lang.StackOverflowError)兩種解決辦法

方法一:

採用@JsonIgnore註解
具體位置如下:

@Entity
@Setter
@Getter
public class BookCategory implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long categoryId;

    @Column(nullable = false, unique = true)
    private String categoryName;

    @JsonIgnore  //在一的一方加的
    @OneToMany(mappedBy = "bookCategoryName", fetch = FetchType.EAGER)
    private Set<Book> categoryBooks= new HashSet<>();
}

多的一方代碼:

public class Book implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long bookId;

    @Column(nullable = false)
    private String bookName;

    @Column(nullable = false)
    private String bookAuthor;

    @Column(nullable = false)
    private String bookPublisher;

    @Column(nullable = false, insertable = false, columnDefinition = "tinyint(1) comment '書籍是否還在書架上'")
    private byte bookStatus;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE, targetEntity = BookCategory.class)
    @JoinColumn(name = "book_category_name", referencedColumnName = "categoryName")
    private BookCategory bookCategoryName;

    //columnDefinition前面必須先指定類型,才能添加註釋,直接添加註釋會出錯
    @Column(nullable = true, columnDefinition = "date comment '登記日期'")
    private LocalDate bookRecord;
}

@JsonIgnore註解並不是簡單的字面意思那樣,不返回被註解的值。從目前我掌握的知識以及結果來看,他或許真的就是簡單的破壞了那個循環鏈。

查詢的結果如下:
在這裏插入圖片描述

方法二:

不知道從上面的返回結果來看,你們發現了什麼祕密沒有。
那就是,book字段中的private BookCategory bookCategoryName,返回的竟然是BookCategory對象中的所有字段。在我們的想象中,我們應該想要的只是BookCategory中的categoryName這個字段的值,但他返回的竟然是一個對象,不符合我們的需求,而且這也是導致循環調用的的元兇

明白了上面的那段話,那麼解決問題的方式就很簡單了。

只要改變private BookCategory bookCategoryName;這個字段的getter方法,讓他返回我們關心的字段就可以了。類似的什麼去掉toString()方法也是沒必要的,只需要在其中改變打印的private BookCategory bookCategoryName;內容即可,還是隻讓他打印我們關心的內容而不是這個對象。

修改代碼如下:

把這段代碼:

public BookCategory getBookCategoryName() {
        return bookCategoryName;
    }

修改成

public String getBookCategoryName() {
        return bookCategoryName.getCategoryName();
	}

總結

  1. 如果想省事,使用@JsonIgnore註解
  2. 如果想在後臺直接把數據格式整理好,就使用第二種方法。
發佈了132 篇原創文章 · 獲贊 86 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章