外键是组合主键的一部分时Hibernate实体映射? [英] Hibernate Entity mapping when Foreign key is part of the composite primary key?
问题描述
我有一个带有复合PK的表:Customer
我有一个没有PK的View:购买
绑定我的实体,Hibernate迫使我声明一个PK。
所以我创建了一个复合PK For Purchase。
购买:
@Entity
@Table(name =PURCHASE)
公共类购买{
@EmbeddedId
私人PurchasePK ID;
}
PuchasePK:
$ b $ private $ String custLastname;
@Column(name =OBJ_NAME)
private long objectName;
}
客户很简单:
@Entity
@Table(name =CUSTOMER)
public class Customer {
@EmbeddedId
私人CustomerPK ID;
$ / code>
借助其复合PK:
@Embeddable
public class CustomerPK {
@Column(name =CUST_LASTNAME)
private String custLastname;
@Column(name =CUST_NAME)
私人长期custName;
}
现在我想通过匹配表CUST_NAME来在Customer中创建一个OneToMany属性。
@OneToMany
私人列表< Purchase> listPurchases;
我该如何做?
我搜索了很多,它总是归结为不能在1列上做FK,如果PK有2列的话......
PS:I' m使用JPA 1,所以我无法访问@MapsId。
PS2:我的真实模型与客户&购买以及用于PKs的属性不是varchar而是Long。 解决方案
直接回答您的问题 - 我认为您无法做到那。
我建议通过引入CUSTOMER_ID字段来重新考虑这个模型,因为第一个+姓氏在实践中并不是独一无二的。此外,由于可能存在Mike Smith,John Smith作为客户,因此仅以姓氏加入会给您带来混购。具有数字ID将解决我所想的所有问题。
I have a Table with a composite PK : Customer I have a View with no PK : Purchase
To bind my Entity, Hibernate forces me to declare a PK. So I've created a composite PK For Purchase.
Puchase:
@Entity
@Table(name = "PURCHASE")
public class Purchase {
@EmbeddedId
private PurchasePK id;
}
PuchasePK:
@Embeddable
public class PurchasePK {
@Column(name = "CUST_LASTNAME")
private String custLastname;
@Column(name = "OBJ_NAME")
private Long objectName;
}
Customer is straight forward :
@Entity
@Table(name = "CUSTOMER")
public class Customer {
@EmbeddedId
private CustomerPK id;
}
With its composite PK:
@Embeddable
public class CustomerPK {
@Column(name = "CUST_LASTNAME")
private String custLastname;
@Column(name = "CUST_NAME")
private Long custName;
}
Now I want to create a OneToMany attribut in Customer by matching both table CUST_NAME.
@OneToMany
private List<Purchase> listPurchases;
How can i do that?
I've searched quite a bit and it always comes down to not being able to do FK on 1 column if the PK has 2 columns ...
PS: I'm using JPA 1, so I don't have access to @MapsId.
PS2: My real model is not about Customer & purchase and the attributs used for the PKs are not varchar but Long.
Answering directly to your question - I think you cannot do that. I would suggest to rethink this model by introducing CUSTOMER_ID field since first+last name quite often are not unique from practice. Moreover joining only by last name will give you mix of purchases since there could be "Mike Smith", "John Smith" as a customers. Having numeric ID will solve all your problems I suppose.
这篇关于外键是组合主键的一部分时Hibernate实体映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!