I'm having a problem setting up a bidirectional association with the one-to-many side as the owner. I will describe my issue using an example from the Hibernate documentation slightly modified.
@Entity
public class Troop {
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name="troop_fk") //we need to duplicate the physical information
public Set<Soldier> getSoldiers() {
...
}
@Entity
public class Soldier {
@ManyToOne()
@JoinColumn(name="troop_fk", insertable=false, updatable=false, nullable = false)
public Troop getTroop() {
...
}
I understand that in the world of databases the owner of the above relationship would be soldier since it has the column with the foreign key, however this does no make sense in real world logic since a soldier is part of a troop and a troop owns a soldier.
I would like to be able to use CascadeType.ALL to automatically save all Soldier when I persist their troop.
The hibernate documentation indicates that:
This solution is not optimized and will produce additional UPDATE statements.
eg. log
Insert Into Troop(id) Values(1)
Insert Into Soldier(id) Values(1)
Insert Into Soldier(id) Values(2)
Update Soldier Set troop_fk = 1 Where id = 1
Update Soldier Set troop_fk = 1 Where id = 2
The problem is that when we first try to insert soldier without the troop_fk an exception is thrown since that column is not nullable.
Why does Hibernate not just add the troop_fk to the insert instead of updating the record later with it? Is there a way for me to do what I described above?