问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/30669034/hibernate-entity-mapping-when-foreign-key-is-part-of-the-composite-primary-key