I am experiencing another behavior than described in the
Hibernate Annotations Reference Guide, so I am wondering if there is a mistake in the Reference Guide.
I try to map a Parent-Child association with a bidirectional list.
Since I am using a list, the parent has to be the owning side of the relationship (no "mappedBy" possible).
I want Hibernate to produce optimal SQL. I expect two SQL-inserts and no SQL-update when creating a new Parent with one new Child.
I am using Hibernate Annotations for the mapping.
The Hibernate Annotations Reference Guide (
Chapter 2.4.6.2.3) suggests the following solution:
On the Parent:
Code:
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "parent_id", nullable=false)
@org.hibernate.annotations.IndexColumn(name = "parent_index")
List<Child> children = new ArrayList<Child>();
On the Child:
Code:
@ManyToOne
@JoinColumn(name = "parent_id", updatable = false, insertable = false, nullable=false)
private Parent parent;
But in this case Hibernate produces three SQL statements when persisting a parent with one child:
Code:
Hibernate: insert into Parent (name, version, id) values (?, ?, ?)
Hibernate: insert into Child (name, price, version, parent_id, parent_index, id) values (?, ?, ?, ?, ?, ?)
Hibernate: update Child set parent_id=?, parent_index=? where id=?
This is not the behavior that the Hibernate Annotations Reference Guide describes!If I repeat the @JoinColumn attributes 'updatable = false' and 'insertable = false' from the Child to the Parent like this:
Code:
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "parent_id", updatable = false, insertable = false, nullable=false)
@org.hibernate.annotations.IndexColumn(name = "parent_index")
List<Child> children = new ArrayList<Child>();
Then Hibernate produces the SQL I am expecting:
Code:
Hibernate: insert into Parent (name, version, id) values (?, ?, ?)
Hibernate: insert into Child (name, price, version, parent_id, parent_index, id) values (?, ?, ?, ?, ?, ?)
I am wondering: Is there a mistake in the The Hibernate Annotations Reference Guide (
Chapter 2.4.6.2.3) ?
Has there been a change in a recent Hibernate release?
Or am I missing something?
See also
this thread for a complete code example.