0

I have a Table with a composite PK : Customer I have a View with no PK : Purchase

enter image description here

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.

TheBakker
  • 2,852
  • 2
  • 28
  • 49
  • having a similar problem: http://stackoverflow.com/questions/31600142/how-to-define-onetomany-in-parent-entity-when-child-has-composite-pk – amphibient Jul 24 '15 at 17:04

1 Answers1

0

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.

Stan
  • 1,410
  • 10
  • 14
  • My real model is not about Customer & Purchase and the composite PK are made from Long not varchar. It was just to write the exemple. – TheBakker Jun 05 '15 at 16:06
  • But correct me if I'm wrong, reference by last name only may lead to situation that one purchase corresponds to few customers with different first names which is incorrect (keep in mind model is about another objects). Or I may assume your CUSTOMER table is many-to-many relation, then it shouldn't be mapped as entity at all. – Stan Jun 05 '15 at 16:14
  • Yes it's a bad idea. But as I said my question wasn't about the model but how to do it technicaly with JPA. – TheBakker Jun 05 '15 at 17:13