Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why hibernate generates insert and update for OneToMany mapping

I am trying to understand the one-to-many mapping in Hibernate with a small example. I have a Product with a set of Part's. 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 save some parts and products in my database and observed below queries generated by hibernate:

Hibernate: insert into Product (serialNumber) values (?)
Hibernate: insert into Part (partName, id) values (?, ?)
Hibernate: update Part set PRODUCT_ID=? where id=?

Here to add a record in Part table, hibernate generates 2 DML operations - insert and update. If a single insert command is sufficient to add a record in table then why hibernate uses both insert and update in this case? Please explain.

like image 928
Chaitanya Avatar asked Aug 19 '14 08:08

Chaitanya


1 Answers

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

Hibernate will switch the insert/update approach to straight inserts if you make the join column not nullable and not updatable, which I assume in your case it is neither anyways:

@JoinColumn(name = "PRODUCT_ID", nullable = false, updatable = false)
like image 160
GhostBytes Avatar answered Sep 20 '22 16:09

GhostBytes