【发布时间】:2020-08-17 12:49:30
【问题描述】:
我有一个 User 表和一个 Book 表要连接。
所以我创建了第三个表 Borrow,它具有外键 (book_id, user_id) 和 takenDate 和 broughtDate 字段。
User.java
@Entity
@Table(name = "Users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String surname;
private String username;
private String email;
private String password;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Borrow> borrow;
....
Book.java
@Entity
@Table(name = "Books")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String title;
private String ISBN;
private String author;
private String issuer;
private Integer dateOfIssue;
private Boolean IsRented;
@OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Borrow> borrow;
.....
Borrow.java
@Entity
@Table(name = "Borrows")
@IdClass(BorrowId.class)
public class Borrow {
private Date takenDate;
private Date broughtDate;
//lazy means it will get details of book
// only if we call GET method
@Id
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "book_id", referencedColumnName = "id")
private Book book;
@Id
@JsonIgnore
@ManyToOne
@JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;
....
BorowId.java
public class BorrowId implements Serializable {
private int book;
private int user;
// getters/setters and most importantly equals() and hashCode()
public int getBook() {
return book;
}
public void setBook(int book) {
this.book = book;
}
public int getUser() {
return user;
}
public void setUser(int user) {
this.user = user;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof BorrowId)) return false;
BorrowId borrowId = (BorrowId) o;
return getBook() == borrowId.getBook() &&
getUser() == borrowId.getUser();
}
@Override
public int hashCode() {
return Objects.hash(getBook(), getUser());
}
}
MySql 数据库设计如下:
我正在尝试将数据添加到 Borrow 表中,如下所示:
已编辑
@Transactional
@PostMapping("/addUser/{id}/borrow")
public ResponseEntity<Object> createItem(@PathVariable int id, @RequestBody Borrow borrow, @RequestBody Book book){
Optional<User> userOptional = userRepository.findById(id);
Optional<Book> bookOptional = bookRepository.findById(book.getId());
if(!userOptional.isPresent()){
throw new UserNotFoundException("id-" + id);
}
User user = userOptional.get();
borrow.setUser(user);
borrow.setBook(book);
borrowRepository.save(borrow);
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(borrow.getId()).toUri();
return ResponseEntity.created(location).build();
}
我还没有完成它,因为我不确定如何:/ 任何提示表示赞赏!
【问题讨论】:
标签: java spring-boot hibernate jpa