我有一个要连接的 User
表和一个 Book
表。
用户可以租用很多书,也可以从许多用户那里租借一本书。
这是 many-to-many
关系。如果我是对的?
因此,我创建了具有外键( Borrow
)的第三个表 bookId, userId
。
User.java
@Entity
@Table(name = "Users")
public class User {
@Id
@GeneratedValue
@Column(name = "user_id")
private Integer id;
private String name;
private String surname;
private String username;
private String email;
private String password;
@OneToMany(mappedBy = "user", cascade = CascadeType.PERSIST)
private List<Borrow> borrow;
//getters and setters
Book.java
@Entity
@Table(name = "Books")
public class Book {
@Id
@GeneratedValue
@Column(name = "book_id")
private Integer id;
private String title;
private String ISBN;
private String author;
private String issuer;
private Integer dateOfIssue;
private Boolean IsRented;
@OneToMany(mappedBy = "book", cascade = CascadeType.PERSIST)
private List<Borrow> borrow;
//getters and setters
Borrow.java
@Entity
@Table(name = "Borrows")
public class Borrow {
@Id
@GeneratedValue
private Integer id;
private Date takenDate;
private Date broughtDate;
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="bookId")
private Book book;
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="userId")
private User user;
当我尝试使用邮递员显示借阅表的详细信息时,只会得到id
,takenDate
,broughtDate
,却看不到userId
或bookId
。
这是我在Postman上运行GET方法后返回的JSON
[
{
"id": 1,
"takenDate": "2020-08-04T00:36:07.000+00:00",
"broughtDate": "2020-08-02T00:36:07.000+00:00"
},
{
"id": 2,
"takenDate": "2020-08-11T00:36:07.000+00:00",
"broughtDate": "2020-07-05T00:36:07.000+00:00"
},
{
"id": 3,
"takenDate": "2020-08-21T00:38:00.000+00:00",
"broughtDate": "2020-08-12T00:38:00.000+00:00"
}
]
获取所有物品的代码:
@GetMapping("/items")
public List<Borrow> getAllItems(){
return service.getAllItems();
}
我不明白为什么不显示外键及其值? 任何建议都将受到高度赞赏。
答案 0 :(得分:0)
您在借阅实体中使用 @JsonIgnore 。将对象序列化为JSON时,将忽略带有JsonIgnore的列。
您在借入实体中使用 延迟加载(FetchType.LAZY) 。如果不使用JsonIgnore,则必须在服务中加载Borrow实体的所有其他实体(Book和User),或者必须使用FetchType.EAGER。