JSON 中不存在 @OneToMany 列
@OneToMany column is not present in JSON
我有以下实体:
Book.java
@Entity @Data
public class Book {
@Id
private Long id;
@Column(unique = true, nullable = false)
private String title;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "book")
@JsonManagedReference
private List<Note> notes;
}
Note.java
@Entity @Data
public class Note {
@Id
private Long id;
@Column(nullable = false)
private String title;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "book_id", nullable = false)
@JsonBackReference
private Book book;
}
当我调用 BookRestController 时,它 returns 一个 JSON 包含我需要的所有属性:
{
"id": 15,
"title": "A fé explicada",
"author": "Leo J. Trese",
"notes": [{
"id": 10,
"title": "Sobre o pecado mortal"
}]
}
但是当我调用 NoteRestController 时,缺少 Book 属性:
{
"id": 10,
"title": "Sobre o pecado mortal"
// missing "book" property here...
}
我做错了什么?
我正在使用 @OneToMany 和 @ManyToOne 注释来声明它是 1-N 关系; @JsonBackReference 和 @JsonManagedReference 的目的很简单,就是避免无限递归。
当然省略了Book
,就是字面上的@JsonBackReference
代表
@JsonBackReference is the back part of reference – it will be omitted from serialization.
(https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion)
解决方案听起来很简单:而不是在您的 REST 控制器中返回 Note
实体(无论如何我尽量避免将实体保留为没有任何实体的实体)无论如何在 REST 上下文中使用)您可以创建一个名为 e 的显式传输对象。 G。 NoteDTO
其中包含对一本书的引用(省略了该书的注释以避免无限递归):
public class NoteDTO {
private Long id;
private String title;
private BookReferenceDTO book;
// getters and setters
}
public class BookReferenceDTO {
private Long id;
private String title;
// getters and setters
}
我有以下实体:
Book.java
@Entity @Data
public class Book {
@Id
private Long id;
@Column(unique = true, nullable = false)
private String title;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "book")
@JsonManagedReference
private List<Note> notes;
}
Note.java
@Entity @Data
public class Note {
@Id
private Long id;
@Column(nullable = false)
private String title;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "book_id", nullable = false)
@JsonBackReference
private Book book;
}
当我调用 BookRestController 时,它 returns 一个 JSON 包含我需要的所有属性:
{
"id": 15,
"title": "A fé explicada",
"author": "Leo J. Trese",
"notes": [{
"id": 10,
"title": "Sobre o pecado mortal"
}]
}
但是当我调用 NoteRestController 时,缺少 Book 属性:
{
"id": 10,
"title": "Sobre o pecado mortal"
// missing "book" property here...
}
我做错了什么?
我正在使用 @OneToMany 和 @ManyToOne 注释来声明它是 1-N 关系; @JsonBackReference 和 @JsonManagedReference 的目的很简单,就是避免无限递归。
当然省略了Book
,就是字面上的@JsonBackReference
代表
@JsonBackReference is the back part of reference – it will be omitted from serialization.
(https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion)
解决方案听起来很简单:而不是在您的 REST 控制器中返回 Note
实体(无论如何我尽量避免将实体保留为没有任何实体的实体)无论如何在 REST 上下文中使用)您可以创建一个名为 e 的显式传输对象。 G。 NoteDTO
其中包含对一本书的引用(省略了该书的注释以避免无限递归):
public class NoteDTO {
private Long id;
private String title;
private BookReferenceDTO book;
// getters and setters
}
public class BookReferenceDTO {
private Long id;
private String title;
// getters and setters
}