Jeremy
Jeremy

Reputation: 3809

How to setup a Hibernate entity that is referenced by multiple foreign keys on a separate table?

I have two tables; one with two foreign keys both referencing the other table. Ex: Game table with a winnerId and loserId columns which are both foreign keys to the Team table's id column.

Now I have a model which I want to be able to call getGames() on which would return a all of the games where the team is either the winner or loser. Is this possible?

I tried @ManyToMany annotations with no luck:

    @ManyToMany
    @JoinTable(name="Game", joinColumns={@JoinColumn(name="winnerId", referencedColumnName="id"), @JoinColumn(name="loserId", referencedColumnName="id")})
    Set<Game> games;

I also tried just creating a query on the repository but it seems extra inefficient.

Upvotes: 0

Views: 20

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

No, not like that. You need two associations: one for the won games, and the other for the lost games. Your getGames() method can simply return the union on the won and lost games.

Upvotes: 1

Related Questions