我有多对多关系:
customer
,product
,customer_product
,附加列quantity
我想用hibernate映射它们我的问题是:
如果我只是像两个一对多那样正常映射它,我会松开什么?
customer_product
只有一个主键(id_customer_product
),而不是复合主键(id_product
+ id_customer
)
customer
实体:
@Entity
@Table(name = "customer", catalog = "XX")
public class Customer implements java.io.Serializable {
@OneToMany(fetch = FetchType.LAZY, mappedBy = "customer")
private Set customer_product = new HashSet<Customer_Product>(0);
}
product
实体:
@Entity
@Table(name = "product", catalog = "XX")
public class Customer implements java.io.Serializable {
@OneToMany(fetch = FetchType.LAZY, mappedBy = "product")
private Set customer_product = new HashSet<customer_product>(0);
}
customer_product
实体:
@Entity
@Table(name = "customer_product", catalog = "XX")
public class Customer_Product implements java.io.Serializable {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "ID_customer_product")
private Integer ID_customer_product;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ID_customer")
private Customer customer;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ID_product")
private Product product;
}
或者我必须像这样制作answer并制作复合主键。
答案 0 :(得分:1)
首先,是客户产品?这看起来像是标准的销售订单模型。
不要让它成为一个简单的多对多关系。双方使用一对多。虽然我没有在任何地方看到您的数量字段,但您已走上正轨。
客户拥有许多客户产品。产品包含许多客户产品。 CustomerProduct属于客户,属于产品。
如果您想使用自动生成的id字段,那么这是您的主键。如果您不希望客户和产品出现重复行,则可以在(客户,产品)上添加唯一约束。