Java – why does hibernate generate inserts and updates for the onetomany map
I try to use a small example to understand the one - to - many mapping in hibernate My product has a set of part's. This is my entity class:
Part. java
@Entity
public class Part {
@Id
@GeneratedValue
int id;
String partName;
//Setters & Getters
}
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;
}
// Setter methods
}
Then I try to save some parts and products in my database and observe the following query generated by Hibernate:
Hibernate: insert into Product (serialNumber) values (?) Hibernate: insert into Part (partName,id) values (?,?) Hibernate: update Part set PRODUCT_ID=? where id=?
To add a record in the part table, hibernate will generate two DML operations - insert and update If a single insert command is enough to add records to a table, why does hibernate use insert and update in this case? Please explain
Solution
I know it's crazy, but I have the same question. Google brought me here, so after repairing, I think I should send an answer
If you make the connection column non empty and non updatable, hibernate will switch the insert / update method to direct insert. I don't think it is any way in your case:
@JoinColumn(name = "PRODUCT_ID",nullable = false,updatable = false)
