【问题标题】:mappedBy refers to the Class Name or to the Table Name?mappedBy 是指类名还是表名?
【发布时间】:2016-11-21 17:28:25
【问题描述】:
例如,当我们在 @OneToMany 中使用 mappedBy 注解时,我们提到了 Class Name 还是 Table Name ?
一个例子:
@Entity
@Table(name = "customer_tab")
public class Customer {
@Id @GeneratedValue public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
private Integer id;
@OneToMany(mappedBy="customer_tab")
@OrderColumn(name="orders_index")
public List<Order> getOrders() { return orders; }
}
那么这两个哪个是正确的? :
- @OneToMany(mappedBy="customer_tab")
- @OneToMany(mappedBy="Customer") ?
谢谢!
【问题讨论】:
标签:
java
hibernate
jpa
mapping
one-to-many
【解决方案1】:
都不对。来自documentation:
映射依据
公共抽象 java.lang.String mappedBy
拥有关系的字段。除非关系是单向的,否则是必需的。
mappedBy 注释表示它标记的字段由关系的另一方拥有,在您的示例中,是一对多关系的另一方。我不确切知道您的架构是什么,但以下类定义是有意义的:
@Entity
@Table(name = "customer_tab")
public class Customer {
@OneToMany(mappedBy="customer")
@OrderColumn(name="orders_index")
public List<Order> getOrders() { return orders; }
}
@Entity
public class Order {
@ManyToOne
@JoinColumn(name = "customerId")
// the name of this field should match the name specified
// in your mappedBy annotation in the Customer class
private Customer customer;
}