关系所有者在Hibernate中意味着什么?

时间:2012-05-08 13:45:05

标签: hibernate hibernate-mapping

@Entity
public class Troop {
    @OneToMany(mappedBy="troop")
    public Set<Soldier> getSoldiers() {
    ...
}

@Entity
public class Soldier {
    @ManyToOne
    @JoinColumn(name="troop_fk")
    public Troop getTroop() {
    ...
}       

我正在努力解决这方面的问题:

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.

例如,以下代码:

Troup t = new Troup();
t.getSoldiers().add(soldier);

如果我刚刚拨打session.saveOrUpdate(t),如果我刚刚打电话,会有什么不同 session.saveOrUpdate(s)? MappedBy将troup定义为所有者,但这具体意味着什么?因为我希望如果我保存士兵对象,肯定会保存troop_fk列吗?如果我只保存troup对象,那么当级联时,士兵外键肯定会正确更新吗?我真的看不出差异。

1 个答案:

答案 0 :(得分:4)

所有者是在刷新时在数据库中设置外键的实体。

代码:

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

没有级联:

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