Yugal Jindle
Yugal Jindle

Reputation: 45656

JPA: How to associate entities with relationship attributes?

We can always do :

EntityA @OneToOne EntityB

@OneToOne
@JoinTable(name="table_name")
private EntityB b;

How will you ?

EntityC @OneToMany EntityD ( But this time I also have EntityType information on join )

But what if you have relationship properties associated ?

Like:

EntityC  -- JoinTable -- EntityD
                |
                |
              EntityType

Now in this case my join table has 3 ids ( EntityC_id, EntityType_id, EntityD_id )

How can I create an association with EntityC and EntityD ( With EntityType ) ?

Upvotes: 0

Views: 1918

Answers (1)

wmorrison365
wmorrison365

Reputation: 6298

I believe the standard way is to create an entity representing JoinTable with @OnetoMany references from your EntityC and EntityD. JoinTable then has its own inverse @ManyToOne references. Such as (from the JPA wikibook on M:N with additional columns):

@Entity
public class EntityC {
  @Id
  private long id;
  ...
  @OneToMany(mappedBy="entityC")
  private List<JoinTable> entityDs;
  ...
}

@Entity
public class EntityD {
  @Id
  private long id;
  ...
  @OneToMany(mappedBy="entityD")
  private List<JoinTable> entityCs;
  ...
}

Your association table is then managed as a separate entity, mapping these two entities to each other:

@Entity
@IdClass(JoinTableId.class)
public class JoinTable {
  @Id
  private long entityCId;
  @Id
  private long entityDId;
  ...
  private int entityTypeId;     //your relationship-attribute
  ...
  @ManyToOne
  @JoinColumn(name="entityCId", referencedColumnName="id", updatable="false", insertable="false")
  private EntityC entityC;
  @ManyToOne
  @JoinColumn(name="entityDId", referencedColumnName="id", updatable="false", insertable="false")
  private EntityD entityD;
  ...
}

public class JoinTableId implements Serializable {
    private long entityCId;
    private long entityDId;
    ...
    //hashCode()
    //equals(...)
}

Note that this is criticised for its duplication and redundancy of id fields across the JoinTable class and its id class, which is required by JPA. See Giannigar's blog for an alternative suggestion (with credits).

N.B. I've hand edited a lot of this so apologies for any typos.

Upvotes: 2

Related Questions