Why does hibernate generate insert and update to display OneToMany

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; //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 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.

+6
source share
4 answers

I know this is crazy old, but I had the same problem and Google brought me here, so after fixing it, I decided that I should post the answer.

Hibernate will switch the insert / update approach to direct inserts if you make the join column invalid and not updatable, which I assume is, in your case, in no way:

 @JoinColumn(name = "PRODUCT_ID", nullable = false, updatable = false) 
+2
source

If Part is like a list of constituent elements, then only two queries will come. Check and return.

If it is not an integral element, hibernate will try to insert a separate element into a separate request, and it will try to create a relationship between them.

In the earlier case, hibernation will be inserted with the relationship key.

0
source

** Hibernation: insert into the values ​​of Product (serialNumber) (?)

Hibernation: insert into the values ​​Part (partName, id) (?,?) **

In these two queries, hibernate simply inserts a record into the database. At this point, sleep mode does not create any connection between the two objects.

Sleep mode: update Package Content PRODUCT_ID =? where id =?

Now, after creating the entity tables, hibernate will establish a relationship between the two using the third query ...

-1
source

Communication is unidirectional, so Product is the owner side (since this is the only party).

Make the association bidirectional and make Part owner of the association. This way you will avoid redundant updates, as foreign key values ​​will be specified as part of the insert statements for Part .

-1
source

Source: https://habr.com/ru/post/974016/


All Articles