Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate JPA ManyToOne composite key

I'm trying to setup my entity to allow to pks. My database consist of two fields,

dealer_detail_id pk user_detail_id pk

Both join on id in corresponding tables.

I've tried this thus far without success.

@Embeddable
public class DealerUserPk implements Serializable {

    private Integer dealerDetail;
    private Integer userDetail;

DealerUser

@Embeddable
@Table(name = "dealer_user", schema = "account") 
public class DealerUser implements Serializable {

    @EmbeddedId
    private DealerUserPk id;

    @Id
    @ManyToOne
    @JoinColumn(name = "dealer_detail_id", referencedColumnName = "id")
    private DealerDetail dealerDetail;

    @Id
    @ManyToOne
    @JoinColumn(name = "user_detail_id", referencedColumnName = "id")
    private UserDetail userDetail;

DealerDetail

@Entity
@Table(name = "dealer_detail", schema = "account") 
public class DealerDetail implements Serializable {

    @Id
    private Integer id;

UserDetail

@Entity
@Table(name = "user_detail", schema = "account") 
public class UserDetail implements Serializable {

    @Id
    private Integer id;

Can anybody spot what I'm doing wrong?

like image 979
Code Junkie Avatar asked Feb 25 '14 01:02

Code Junkie


People also ask

How can we create composite key in Hibernate?

A composite primary key is mapped using an Embeddable type in hibernate. We'll first create an Embeddable type called EmployeeIdentity containing the employeeId and companyId fields, and then create the Employee entity which will embed the EmployeeIdentity type.

How do you define a composite primary key in Hibernate HBM XML?

We can create a composite key using an XML mapping file. In that mapping file, we are using a <composite-id>… <composite-id/> tag to declare a composite key. All the primary key objects of the POJO class are defined inside the composite key tag.


1 Answers

This is correct:

@Embeddable
public class DealerUserPk implements Serializable {

    private Integer dealerDetail;
    private Integer userDetail;
  1. But your DealerUser is annotated with embeddable it should be @Entity as you are using @Table annotation.
  2. Need to add MapsId as it follows

     @Entity
     @Table(name = "dealer_user", schema = "account") 
      public class DealerUser implements Serializable {
    
    @EmbeddedId
    private DealerUserPk id;
    
    @MapsId("dealerDetail")
    @ManyToOne
    @JoinColumn(name = "dealer_detail_id", referencedColumnName = "id")
    private DealerDetail dealerDetail;
    
    @Id
    @MapsId("userDetail")
    @JoinColumn(name = "user_detail_id", referencedColumnName = "id")
    private UserDetail userDetail;
    

Try with that.

like image 191
Koitoer Avatar answered Sep 27 '22 22:09

Koitoer