I am trying to understand the one-to-many mapping in Hibernate with a small example. I have a Product with Part's kit. Here are my entity classes:
Part.java
@Entity public class Part { @Id @GeneratedValue int id; String partName;
Product.java
@Entity public class Product { private String serialNumber; private Set<Part> parts = new HashSet<Part>(); @Id public String getSerialNumber() { return serialNumber; } @OneToMany @JoinColumn(name = "PRODUCT_ID") public Set<Part> getParts() { return parts; }
Then I tried to store some parts and products in my database and watched below the queries generated by the sleeper:
Hibernate: insert into Product (serialNumber) values (?) Hibernate: insert into Part (partName, id) values (?, ?) Hibernate: update Part set PRODUCT_ID=? where id=?
Here, to add an entry to the Part table, hibernate generates 2 DML operations - insert and update . If a single insert command is enough to add a record to a table, then why does hibernate use both insert and update in this case? Please explain.
source share