3 回答

TA贡献1828条经验 获得超13个赞
令人难以置信的是,在过去的三年中,没有人用两种方式来描述您的关系来回答您的出色问题。
正如其他人所提到的,“所有者”端在数据库中包含指针(外键)。您可以将任一侧指定为所有者,但是,如果将一侧指定为所有者,则关系将不会是双向的(反向(也称为“许多”侧)将不知道其“所有者”)。这对于封装/松散耦合可能是理想的:
// "One" Customer owns the associated orders by storing them in a customer_orders join table
public class Customer {
@OneToMany(cascade = CascadeType.ALL)
private List<Order> orders;
}
// if the Customer owns the orders using the customer_orders table,
// Order has no knowledge of its Customer
public class Order {
// @ManyToOne annotation has no "mappedBy" attribute to link bidirectionally
}
唯一的双向映射解决方案是让“许多”一侧拥有其指向“一个”的指针,并使用@OneToMany“ mappedBy”属性。如果没有“ mappedBy”属性,Hibernate将期望进行双重映射(数据库将同时具有连接列和连接表,这是多余的(通常是不希望的))。
// "One" Customer as the inverse side of the relationship
public class Customer {
@OneToMany(cascade = CascadeType.ALL, mappedBy = "customer")
private List<Order> orders;
}
// "many" orders each own their pointer to a Customer
public class Order {
@ManyToOne
private Customer customer;
}
添加回答
举报