简体   繁体   中英

JPA modelling, one-to-one relation?

I am new to JPA and stuggles with defining the relations between my classes. I have a class called Player and a class called Game. A game holds references to two Player instances. The question is, how should this be modelled?

This is my current code:

@Entity
@Table(name = "t_player")
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class Player {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Basic
    @Column(name = "name")
    private String name;

    @Basic
    @Column(name = "uuid")
    private final String uuid = UUID.randomUUID().toString();

I think this is ok, but my problem is in the Game class:

@Entity
@Table(name = "t_game")
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class Game {

    public Game() {

    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Basic
    @Column(name = "uuid")
    private final String uuid = UUID.randomUUID().toString();

    @OneToOne
    @PrimaryKeyJoinColumn
    @JoinColumn(name = "id")
    private Player player_1;

    @OneToOne
    @PrimaryKeyJoinColumn
    @JoinColumn(name = "player_2")
    private Player player_2;

    public Game(Player player_1, Player player_2) {
        this.player_1 = player_1;
        this.player_2 = player_2;
    }

}

This is not working, my table t_game only has two field; id and uuid. Where is my problem?

Remove the PrimaryKeyJoinColumn annotation, as I don't think it is what you meant to use, as it conflicts with the joincolumn definition. Use the joincolumn annotation instead to define the foreign key field name and the field it references if necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM