多対多でSpringJpa、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ご注意戻り値が注釈されていないような単純な文字通りの意味ではありません。私の現在の知識との結果から、おそらく彼は本当にループチェーンの単純な破壊です。

次のようにクエリ結果は以下のとおりです。
ここに画像を挿入説明

方法2:

私はあなたが秘密を発見していないが、このような観点から返された結果を知りません。
これは、本分野で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. あなたは、バックグラウンドで直接データ形式を整理したい場合は良いですが、あなたは第二の方法を使用します。
公開された141元の記事 ウォンの賞賛131 ビュー210 000 +

おすすめ

転載: blog.csdn.net/qq_41621362/article/details/103997237