getSoldiers() { ... ...">

What does a relationship owner in Hibernate mean?

@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 the 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 difference does it make if I just call session.saveOrUpdate(t) and if I just call session.saveOrUpdate(s) ? MappedBy defines the corpse as the owner, but what exactly does that mean? Because I would expect that if I save the soldier object, will the troop_fk column be saved correctly? And if I just save the troupe's object, surely the soldier’s foreign key will still be correctly updated when cascading? I really don't see the difference.

+7
source share
1 answer

owner is an object that installs a foreign key in the database when flushing.

the code:

 Troup t = new Troup(); t.getSoldiers().add(soldier); session.SaveOrUpdate(t); session.Flush(); 

without cascading:

 throws references transient instances 

with cascade and owner = squad

 INSERT INTO troops (id, ...) VALUES (1, ...) INSERT INTO soldiers (..., troop_fk) VALUES (..., NULL) UPDATE soldiers SET troop_fk=1 <- troop sets its key 

with cascade and owner = soldier

 INSERT INTO troops (id, ...) VALUES (1, ...) INSERT INTO soldiers (..., troop_fk) VALUES (..., 1) <- soldier saves the reference 
+4
source

All Articles