What does a relationship owner mean in Hibernate?
hibernate, hibernate-mapping
Solution
the owner is the entity which sets the foreign key in the database on flushing.
the code:
Troup t = new Troup();
t.getSoldiers().add(soldier);
session.SaveOrUpdate(t);
session.Flush();
without cascading:
throws references transient instances
with cascading and owner = troop
INSERT INTO troops (id, ...) VALUES (1, ...)
INSERT INTO soldiers (..., troop_fk) VALUES (..., NULL)
UPDATE soldiers SET troop_fk=1 <- troop sets its key
with cascading and owner = soldier
INSERT INTO troops (id, ...) VALUES (1, ...)
INSERT INTO soldiers (..., troop_fk) VALUES (..., 1) <- soldier saves the reference
Problem
``` @Entity public class Troop { @OneToMany(mappedBy="troop") public Set<Soldier> getSoldiers() { ... } @Entity public class Soldier { @ManyToOne @JoinColumn(name="troop_fk") public Troop getTroop() { ... } ``` I am struggling with documentation on this: ``` Troop has a bidirectional one to many relationship with Soldier through the troop property. You don't have to (must not) define any physical mapping in the mappedBy side. ``` So for example the following code: ``` Troup t = new Troup(); t.getSoldiers().add(soldier); ``` What would the difference be if I just called `session.saveOrUpdate(t)`, and if I just called `session.saveOrUpdate(s)`? MappedBy defines troup as the owner, but what specifically does this mean? Because I would expect that if I save the soldier object, surely the troop_fk column will be saved correctly? And if I just save the troup object, surely the the soldier foreign key will still be update correctly when cascading? I really can't see the difference.