在Hibernate中,关系所有者意味着什么?
@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对象,当级联时士兵外键肯定会正确更新? 我真的看不出差别。
所有者是在数据库中设置外键的实体。
代码:
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
链接地址: http://www.djcxy.com/p/59375.html
上一篇: What does a relationship owner mean in Hibernate?
下一篇: How to make a nav