Hibernate Entity mapping when Foreign key is part of the composite primary key?

蓝咒 提交于 2019-12-12 02:17:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!