I have an entity class called user with the following code:
@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);
}
below is the code for books table
@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
Below is the code for borrowed books entity 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
}
The hibernate code for adding the borrowed book code is as follows:
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
I am trying to implement this code using 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
}
As seen from the code above, I can access the userId from the frontend, but how am I to replicate the object creation seen in the hibernate code here? I need to access the bookName and genre from the frontend along with the user id. I am using postman as a rest client for the time being.