Von
Von

Reputation: 178

Mapping JPA Composite Foreign Key

I'm new with JPA, and want to create a Database with this relation :

|Participant|
|id : INT (PK) | id_event : INT (PK, FK) |

|Event|
|id : INT (PK) |

I'm totally lost and barely figure the syntax of the examples I found :/

But I understood I need to create an other class to contain the two pieces of the PK, which leads to another question : can this class be an inner-class (for optimisation purposes) ?

I hope I'm not asking too much but I really want to get it.

Upvotes: 1

Views: 305

Answers (2)

sanastasiadis
sanastasiadis

Reputation: 1202

For a OneToMany relation you need the below entities and tables:

  • Participant
  • Event

The Event entity is simple:

@Entity
public class Event {
    @Id
    private Long id;

    // fields, constructors, getters, setters
}

The entity Participant has to hold the composite key (aka two pieces of the PK), so, every Participant is only linked once with an Event.

@Entity
public class Participant {
    @EmbeddedId
    private EventParticipantPK id;

    @OneToMany(fetch = FetchType.LAZY)
    private List<Event> events;

    // fields, constructors, getters, setters
}

The composite key is declared as an EmbeddedId.

The EventParticipantPK should be like:

@Embeddable
public class EventParticipantPK {
    @Column (name = "PARTICIPANT_ID")
    private Long participantId;

    @Column (name = "EVENT_ID")
    private Long eventId;

    // fields, constructors, getters, setters
}

I hope this helps.

Upvotes: 1

DimaSan
DimaSan

Reputation: 12684

Your entities might be like this:

@Entity
public class Participant {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany(fetch = FetchType.LAZY)    // or any other relation
    private List<Event> events;

    // fields, constructors, getters, setters
}

@Entity
public class Event {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // fields, constructors, getters, setters
}

In this case JPA will create 3 tables with the following queries (SQL dialect will vary from DB to DB, in this case I used H2 database):

CREATE TABLE Event (
  id bigint GENERATED BY DEFAULT AS IDENTITY,
  PRIMARY KEY (id)
);

CREATE TABLE Participant (
  id bigint GENERATED BY DEFAULT AS IDENTITY,
  PRIMARY KEY (id)
);

CREATE TABLE Participant_Event (
  Participant_id bigint NOT NULL,
  events_id      bigint NOT NULL
)

Participant_Event is automatically created join table to link participants and events.

Here is a good example of understanding JPA entity relations.

Upvotes: 1

Related Questions