Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: Two OneToMany properties, mapped by the same entity with different columns

I know that this can be easily solved with an HQL query, however I prefered to simply have Hibernate handle this with a few OneToMany properties for me.

Let me demonstrate what I want my domain model to look like in pseudo-code:

Game
  Long GameID
  Team HomeTeam
  Team AwayTeam
  @OneToMany(mappedBy="team")
  Set<TeamPlay> HomeTeamPlays
  @OneToMany(mappedBy="team")
  Set<TeamPlay> AwayTeamPlays

The table structure is similar, there are two foreign keys that both point to the Team table on the Game table. Clearly if there were only one foreign key then it would represent a true One-To-Many relationship but in reality what I want is two bi-directional One-To-Many properies for the same entity child type.

I don't believe using the @Where annotation will work as it requires a constant, and @JoinColumn is not allowed here. If it is not possible then that is okay, I just wanted to here it from somebody else.

like image 891
maple_shaft Avatar asked Feb 19 '23 03:02

maple_shaft


1 Answers

I bet you don't really understand the use of mappedBy.

You may refer to my other answer in https://stackoverflow.com/a/13812047/395202

In short, mappedBy is the property name in the "opposite side" of a bi-directional relationships.

For you case, it probably look something like:

class TeamPlay {
    @ManyToOne
    Team homeTeam;

    @ManyToOne
    Team awayTeam;
}

class Team {
    @OneToMany(mappedBy="homeTeam")
    Set<TeamPlay> homeTeamPlays;

    @OneToMany(mappedBy="awayTeam")
    Set<TeamPlay> awayTeamPlays;
}
like image 81
Adrian Shum Avatar answered Mar 15 '23 22:03

Adrian Shum