【问题标题】:What does a relationship owner mean in Hibernate?Hibernate 中的关系所有者是什么意思?
【发布时间】:2012-05-17 00:15:50
【问题描述】:
@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 对象,那么士兵外键在级联时肯定会正确更新吗?我真的看不出有什么区别。

【问题讨论】:

    标签: hibernate hibernate-mapping


    【解决方案1】:

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

    代码:

    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
    

    【讨论】:

    • 有关更多信息,请查看第 2.2.5.3.1.1 节。在docs.jboss.org/hibernate/annotations/3.5/reference/en/…。在上面的示例中,包含有关如何将所有权从一个实体切换到另一个实体的信息。
    • 具有级联和所有者 = 部队,插入士兵 (..., 部队_fk) 值 (..., NULL)。如果在士兵表中,top_fk 不可为空,则在执行查询时将出现休眠错误。是开发人员必须处理的吗?
    • 如果该列不可为空,您根本不能使用“级联和所有者 = 部队”
    猜你喜欢
    • 2012-04-04
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多