title: Hibernate one to one for two columns (two fields of the same type in an Entity class)
body: <p>Suppose I have a Noughts and Crosses game (tic tac toe):</p>
  
  <p><strong>games</strong>:</p>
  
  <pre><code>id    crosses_player_id    noughts_player_id...
  </code></pre>
  
  <p><strong>players</strong>:</p>
  
  <pre><code>id    alignment    game_id
  </code></pre>
  
  <p>Since there are only 2 players, I see no need to create a separate table, so I did it like this:</p>
  
  <pre><code>@Entity
  @Table(name = "games")
  public class Game {
      @Id @GeneratedValue
      private int id;
  
      @OneToOne(mappedBy = "game")
      @JoinColumn(name = "crosses_player_id")
      private Player crossesPlayer;
      @OneToOne(mappedBy = "game")
      @JoinColumn(name = "noughts_player_id")
      private Player noughtsPlayer;
  
      private List&lt;Move&gt; moves = new ArrayList&lt;&gt;();
      private List&lt;Field&gt; fields = new ArrayList&lt;&gt;();
  ...
  </code></pre>
  
  <pre><code>@Entity
  @Table(name = "players")
  public class Player {
      @ManyToOne
      @JoinColumn(name="user_id", nullable=false)
      private User user;
  
      private enum Alignment {
          NOUGHTS, CROSSES
      };
      private Alignment alignment;
  
      @OneToOne(mappedBy = ?)
      private Game game;
  ...
  </code></pre>
  
  <p>However I'm not sure what to put inside <code>@OneToOne(mappedBy = ?)</code> in <code>Player</code> class.</p>
  
  <p>The closest answer I've found is this one:</p>
  
  <p><a href="https://stackoverflow.com/a/13944195/4759176">https://stackoverflow.com/a/13944195/4759176</a></p>
  
  <pre><code>class TeamPlay {
      @ManyToOne
      Team homeTeam;
  
      @ManyToOne
      Team awayTeam;
  }
  
  class Team {
      @OneToMany(mappedBy="homeTeam")
      Set&lt;TeamPlay&gt; homeTeamPlays;
  
      @OneToMany(mappedBy="awayTeam")
      Set&lt;TeamPlay&gt; awayTeamPlays;
  }
  </code></pre>
  
  <p>However it looks like <code>Team</code> class can have many possible games, while in my case 1 player has only ever 1 game. A player is basically users's id, game's id and the allighment (noughts or crosses) and after the game is over that same player is never referenced again from any new games. Maybe I should do it like this:</p>
  
  <p><strong>Player</strong>:</p>
  
  <pre><code>@OneToOne(mappedBy = "crossesPlayer")
  private Game crossesGame;
  
  @OneToOne(mappedBy = "noughtsPlayer")
  private Game noughtsGame;
  </code></pre>
  
  <p>but then, a player can <em>only</em> be either noughts or crosses player, so one of those fields would always be null?</p>