如何解决用外键联接两个表-Hibernate,SpringBoot
我有一个要连接的 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();
}
我不明白为什么不显示外键及其值? 任何建议都将受到高度赞赏。
解决方法
-
您在借阅实体中使用 @JsonIgnore 。将对象序列化为JSON时,将忽略带有JsonIgnore的列。
-
您在借入实体中使用 延迟加载(FetchType.LAZY) 。如果不使用JsonIgnore,则必须在服务中加载Borrow实体的所有其他实体(Book和User),或者必须使用FetchType.EAGER。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。