broschb broschb - 3 months ago 16
Java Question

jpa hibernate composite foreign key mapping

I am having trouble setting up jpa mappings for some entities. I have a parent entity defined like the following.

public class InstanceEntity implements Serializable{

private static final long serialVersionUID = 1L;

@Column(name = "EAIH_ID")
private Long eaihid;
@Column(name = "EAD_ID")
private Long eadid;

@OneToMany(targetEntity=InstanceNotifyEntity.class, mappedBy="instance",fetch=FetchType.EAGER, cascade = CascadeType.ALL)
private List<InstanceNotifyEntity> userDetails = new ArrayList<InstanceNotifyEntity>();

I then have a child entity w/ a composite key, and a foreign key to the primary key of this table as follows:

public class InstanceNotifyEntity implements Serializable{

private static final long serialVersionUID = 1L;

@JoinColumn(name="EAIH_ID", referencedColumnName="EAIH_ID")
private InstanceEntity instance;

private Long userId;
private String commentText;

I know the child entity is incorrect, but I am unsure how to set this up to have a composite PK. I know I need to setup a PK class, but I am not sure how to do that when one field is a foreign key to the parent class. And once that is setup how would the parent reference the child entity?

Any help is appreciated.


This is governed by JPA 2 spec section 2.4.1, "Primary Keys Corresponding to Derived Identities". The section contains two examples directly applicable to your problem.

As described in the spec, there are two ways to represent the child entity's key in this case:

  • @IdClass
  • @EmbeddedId

Here's a rough sketch of the EmbeddedId way. I chose EmbeddedId arbitrarily, but the choice between IdClass and EmbeddedId is significant. You might choose differently.

// Child entity's composite primary key
public class InstanceNotifyEntityId implements Serializable {
    Long eaihId;
    Long userId;

// Child entity
public class InstanceNotifyEntity implements Serializable {
      @AttributeOverride(name="userId", column = @Column(name="USER_ID"))
      @AttributeOverride(name="eaihId", column = @Column(name="EAIH_ID"))
    InstanceNotifyEntityId id;

    InstanceEntity instance;

    // ...

The parent entity needs one change: the userDetails attribute mappedBy should be "id.eaihId". I think that's it, but I haven't used entities exactly like this before. Might have missed something... please post if you see errors.