There are two table entities with a one-to-many relationship. I use Spring Data + JPA.
@Entity @Table(name = "owners") @NamedEntityGraph(name = "Owner.books", attributeNodes = @NamedAttributeNode("books")) public class Owner implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "owner_id", nullable = false, unique = true) private Long id; @Column(name = "owner_name", nullable = false) private String name; @OneToMany(fetch = FetchType.LAZY,mappedBy = "owner") private Set<Book> books= new HashSet<>(0); } @Entity @Table(name = "books") @NamedEntityGraph(name = "Book.owner", attributeNodes = @NamedAttributeNode("owner")) public class Book implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "book_id", unique = true, nullable = false) private Long id; @Column(name = "book_name", nullable = false, unique = true) private String name; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "owner_id") private Owner owner; } In the controller class of these entities, I make the ViewModel , which I send to the client on the html page. On the client side, I make changes to the ViewModel — I change the name or add / delete the Books (I actually work with the ID of the books) from OwnerViewModel . Then I send the modified OwnerViewModel object back to the server, mapping from OwnerViewModel -> Owner . And I need to save this Owner with the added / removed Book.
Well, the problem here is - I don’t know how to save Owner - because after mapping from the client’s side, only a set of ID books comes. How can I save the new updated Owner to the database?
public class OwnerViewModel { private Long id; private String name; private Set<BookSimpleInfo> books= new HashSet<>(0); } public class BookSimpleInfo { private Long id; } Does anyone have any ideas? need help