[英]One-to-many unidirectional relationship using spring boot
我有一个名为 user 的实体 class ,代码如下:
@Table(name="user")
public class User {
//one-to-many relationship with borrowed books
@OneToMany(mappedBy="user", cascade = CascadeType.ALL)
@JoinColumn(name="user_id")
private List<BorrowedBooks> borrowedBooks;
//define fields
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private Integer id;
@Column(name="first_name")
private String firstName;
// getters and setters go here
//this is the method used to add the borrowed books
public void addBorrowedBook(BorrowedBooks borrowedbook) {
if(borrowedBooks==null) {
borrowedBooks = new ArrayList<>();
}
borrowedBooks.add(borrowedbook);
}
下面是书籍表的代码
@Entity
@Table(name="books")
public class Books {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private Integer Id; // autogenerated unique values.
@Column(name="title")
private String title;
@Column(name="genre")
//getters and setters go here
下面是借书实体 class 的代码:
public class BorrowedBooks {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
@Column(name="id")
private Integer id;
@Column(name="bookName")
private String bookName;
@Column(name="genre")
private String genre ;
//getters and setters goes here
}
添加借书代码的hibernate代码如下:
User newUser = new User(1,"john doe") //the values are userId,first_name
newUser.addBorrowedBook(new BorrowedBooks(1,"love to code", "computer science")); //values are id,book name, genre
session.save(newUser) // this saves the user along with the borrowed book details with userId as foreignKey into the database
我正在尝试使用 spring rest controller 来实现此代码
@RestController
@RequestMapping("/base path goes here")
public class BorrowedBooksRestController {
private BorrowedBooksService borrowedBooksService;
public BorrowedBooksRestController(BorrowedBooksService borrowedBooksService) {
this.borrowedBooksService = borrowedBooksService;
}
@PostMapping("/users")
public void addBorrowedBooks(@RequestBody User theUser) {
//this allows me to access the user id which is the foreign key for the borrowedBooks entity class but I need to access the borrowedBooks details as well such as bookName, genre etc.
How do I send values from both user and borrowed books entity class.
borrowedBooksService.save()//here we add the borrowedBook object to save in the database
}
从上面的代码可以看出,我可以从前端访问 userId,但是我如何复制 hibernate 代码中看到的 object 创建? 我需要从前端访问 bookName 和流派以及用户 ID。 我暂时使用 postman 作为 rest 客户端。
对于您的任务,您需要前端的 userId 和 bookId 都传递给 addBorrowedBook controller。如果您有 bookId,因为 bookId 是图书实体的主键,您可以唯一标识这本书。 无需知道书籍类型或名称。 因此,从 bookId 中,您可以从书表中获取数据并创建书 object。 然后,您可以将该书 object 添加到用户 object 借书列表并保存/更新,如示例代码中所示。
否则,如果您的表格不包含表格中的书籍详细信息,则您没有其他选择,而不是从前端传递书籍类型等。
以这种方式传递书籍信息以及 userId。
@postMapping('/user')
public void addBorrowedBook(@RequestParam int userId, @RequestParam String genre, @RequestParam Stringbookname)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.