There are two entities

@Entity @Table(name = "BOOKS") public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "TITLE") private String title; @Column(name = "BOOK_PRICE") private int price; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "AUTHOR_ID") private Author author; @Entity @Table(name = "AUTHOR") public class Author { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "NAME") private String name; @Column(name = "YEARS") private String years; @OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) private Set<Book> books; 

The saving of the book in the database does not work, it says that the author_id field cannot be null, although I tried to manually complain the author:

 @PostMapping("/add") public String add(@ModelAttribute("book")Book book){ Author author = new Author(); author.setName("Гоголь Н.В."); author.setYears("1809 - 1852"); Set<Book> books = new HashSet<>(); books.add(book); author.setBooks(books); book.setAuthor(author); bookService.addBook(book); return "redirect:/home"; } 

I think it's in the form of adding. But I don’t understand how you can send the author as well.

 <form name="book" action="/add" method="post"> <p>Title</p> <input title="Title" type="text" name="title"> <p>Price</p> <input title="Price" type="text" name="price"> <input type="submit" value="Ok"> </form> 

For help I will be grateful

  • You added the author only at the code level and in the database it does not exist, respectively, and id is empty - JVic

1 answer 1

Here is what you can say about the @ManyToOne annotation.

Defines a unique relationship to another essential class that has a plural plurality. Usually there is no need to specify the target object explicitly, since it can usually be inferred from the type of the object being referenced. If the relationship is bidirectional, the party not owning @OneToMany must use the mappedBy element to specify the relationship field or the property of the object that owns the relationship.

Since you create essence manually, it still has no connection and therefore such essence does not represent multiplicity. In order to display the target object, it is not necessary to specify it, but rather to load it, then the owner will take into account the type of the object when saving, to which the reference is made.