8
@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.

mogronalol
  • 2,946
  • 8
  • 38
  • 56

1 Answers1

5

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
Firo
  • 30,626
  • 4
  • 55
  • 94
  • For more information check section 2.2.5.3.1.1. at http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-mapping-association. With info on how to toggle the ownership from one entity to another for the above example. – Master Chief Feb 07 '16 at 11:24
  • with cascading and owner = troop, INSERT INTO soldiers (..., troop_fk) VALUES (..., NULL). If in soldiers table toop_fk is not nullable then while executing the query will hibernate thows error. Is it developer has to take care of that? – Aslam a Jan 09 '17 at 06:09
  • if the column is not nullable you simply can't use "cascading and owner = troop" – Firo Jan 12 '17 at 13:55