我正在嘗試創建多對多關系。我有一個表“library_branch”,我想加入包含“bookId”、“branchId”和“noOfCopies”的“BookCopies”。我有一個錯誤ErrorMvcAutoConfiguration$StaticView。我不確定我在哪里導致這種無限遞回,任何幫助將不勝感激。
2021-11-26 14:54:43.544 ERROR 22348 --- [nio-8080-exec-1] s.e.ErrorMvcAutoConfiguration$StaticView : Cannot render error page for request [/api/branch] and exception [Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: com.example.demo.branch.Branch["inventory"]->org.hibernate.collection.internal.PersistentSet[0]->com.example.demo.inventory.Inventory["branch"]->com.example.demo.branch.Branch["inventory"]

庫存Id.java
package com.example.demo.inventory;
...
@Data @AllArgsConstructor
@NoArgsConstructor
@Embeddable
public class InventoryId implements Serializable {
@Column(name = "book_id")
private int bookId;
@Column(name = "branch_id")
private int branchId;
}
庫存.java
package com.example.demo.inventory;
...
@Entity(name="Inventory")
@Table(name = "tblBookCopies")
public class Inventory {
@EmbeddedId
private InventoryId id;
@ManyToOne(fetch = FetchType.LAZY)
@MapsId("branch_id")
private Branch branch;
@ManyToOne(fetch = FetchType.LAZY)
@MapsId("book_id")
private Book book;
@Column(name="no_of_copies")
private int qty;
public Inventory( Branch branch, Book book, int qty) {
this.id = new InventoryId(branch.getId(),book.getId());
this.branch = branch;
this.book = book;
this.qty = qty;
}
...
}
分支.java
package com.example.demo.branch;
...
@Entity(name="Branch")
@Table(name="tblLibraryBranch")
public class Branch {
@Id
@Column(name="id")
private int id;
@Column(name="name")
private String name;
@Column(name="address")
private String address;
@OneToMany(mappedBy = "branch", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Inventory> inventory = new HashSet<>();
...
}
uj5u.com熱心網友回復:
問題是你Inventory指向Branch和你Branch有一個對Inventory. 問題來自杰克遜,你需要解釋它如何遵循這些形成回圈依賴的參考。
選項1)
不要使用物體進行序列化。通常你不想暴露 DB 物體 - 這些應該是內部物件。如果將它們映射到某些 DTO 表示并序列化,則問題將消失。
選項 2)
向杰克遜解釋如何遵循這些參考資料 - 您需要查看JsonManagedReference和JsonBackReference。
在您的情況下,您需要嘗試類似的操作(但還要檢查此博文中的第 7 條):
@Entity(name="Inventory")
@Table(name = "tblBookCopies")
public class Inventory {
...
@ManyToOne(fetch = FetchType.LAZY)
@MapsId("branch_id")
@JsonManagedReference // <-------- THIS
private Branch branch;
...
}
和
@Entity(name="Branch")
@Table(name="tblLibraryBranch")
public class Branch {
...
@OneToMany(mappedBy = "branch", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonBackReference // <--------- THIS
private Set<Inventory> inventory = new HashSet<>();
...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/368503.html
上一篇:如何對字串進行排序并檢查字謎?
下一篇:pivot_wider溶解排列
