user1154644
user1154644

Reputation: 4609

JPA Link Tables

I am trying to create a link table to link parents/children, both of which are of the same type (person). I'm also trying to create a link table to link players to teams.

In the Team Class, I have:

    @OneToMany
@JoinTable(name = "PLAYER_TEAM_LINK",
        joinColumns = {
    @JoinColumn(name = "TEAM_ID")},
        inverseJoinColumns = {
    @JoinColumn(name = "PLAYER_ID")})
private List<Player> players;

In the Player Class, I have:

    @ManyToOne
@JoinTable(name = "PLAYER_TEAM_LINK",
        joinColumns = {
    @JoinColumn(name = "PLAYER_ID")},
        inverseJoinColumns = {
    @JoinColumn(name = "TEAM_ID")})
private Team team;

For the 2nd scenario, in my Person class, I have:

    @ManyToMany(mappedBy = "children")
private List<Person> parents;
@ManyToMany
@JoinTable(name = "PARENT_CHILD_LINK",
        joinColumns =
        @JoinColumn(name = "PARENT_ID"),
        inverseJoinColumns =
        @JoinColumn(name = "CHILD_ID"))
private List<Person> children;

So basically what I am trying to do is generate a link table to link a parent to a child (so the parent id and child id combo would be the primary key), and a parent can have multiple children.

Then, I am trying to create a link table to link teams with players (so the player id and team id combo would be the primary key).

I'm using hibernate as the provider and am using a plugin to do the schema generation, but I can't find the right combination of @ManyToOne, @ManyToMany, etc to generate the link tables with the composite primary keys.

Any help would be appreciated.

Upvotes: 0

Views: 830

Answers (2)

Andreas Aumayr
Andreas Aumayr

Reputation: 1006

Personally I like this page very much: http://en.wikibooks.org/wiki/Java_Persistence it covers lots of different topics concerning the JPA. Especially, you may find the section about the different relation types useful:

http://en.wikibooks.org/wiki/Java_Persistence/OneToOne http://en.wikibooks.org/wiki/Java_Persistence/ManyToOne http://en.wikibooks.org/wiki/Java_Persistence/OneToMany http://en.wikibooks.org/wiki/Java_Persistence/ManyToMany http://en.wikibooks.org/wiki/Java_Persistence/Embeddables

For each relation type, there are some pretty good examples given.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691715

Your Team-Player association is mapped incorrectly. You're repeating yourself, by declaring how this unique, bidirectional association is mapped twice: once in Team, and once more in Player. One side (the Team side in this case) must be the inverse side by using the mappedBy attribute:

@OneToMany(mappedBy = "team")
private List<Player> players;

The rest looks correct to me.

I don't see why you're using a join table to map this bidirectional ManyToMany though. Why not simply use a join column in the Player table?

Upvotes: 1

Related Questions