8
@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 对象,那么士兵外键在级联时肯定会正确更新吗?我真的看不出有什么区别。

4

1 回答 1

5

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

编码:

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

没有级联:

throws references transient instances

具有级联和所有者 = 部队

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

级联和所有者=士兵

INSERT INTO troops (id, ...) VALUES (1, ...)
INSERT INTO soldiers (..., troop_fk) VALUES (..., 1) <- soldier saves the reference
于 2012-05-14T13:35:03.510 回答