【问题标题】:Mapping many-to-many relationship映射多对多关系
【发布时间】:2014-08-17 11:35:14
【问题描述】:

我有一个多对多的关系:

customerproductcustomer_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 并创建一个复合主键。

【问题讨论】:

    标签: sql database hibernate jpa


    【解决方案1】:

    首先,什么是客户产品?这看起来像一个标准的销售订单模型。

    不要让它成为简单的多对多关系。两边都使用一对多。您走在正确的轨道上,尽管我在任何地方都看不到您的 Quantity 字段。

    一个客户有许多客户产品。一个产品有许多客户产品。客户产品属于客户和产品。

    如果您想使用自动生成的 id 字段,那么这就是您的主键。如果您不希望客户和产品重复行,则可以在 (customer,product) 上添加唯一约束。

    【讨论】:

    • 谢谢,很清楚。但是对于没有额外列的多对多 relashioship 最好是像这样link 并且不创建自动生成的 id 字段(伪键)?
    • Hibernate 建议在大多数情况下使用无意义的代理键,所以我会将其作为默认选择。
    猜你喜欢
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多