Search code examples
springdatabasehibernatejpapersistence

Is possible to have a Composite Primary Key which components are entity foreign keys?


I have the following model:

(...)
@IdClass(BetID.class)           //Primary Key, composite = userID+gameID
public class Bet {

(...)
//Primary Key
@ManyToOne
    @Id
    private User user;          //Composite key:userID
    @ManyToOne
    @Id
    private Game game;          //Composite key:gameID

In which, of course, has the following Composite key:

public class BetID implements Serializable {

    @OneToOne
    private User user;
    @OneToOne
    private Game game;

Here, User and Game are foreign keys, but also entities. Problem is when I'm trying to handle, so I can't set/get the key as easy as having a normal key like: @EmbeddedId BetID bet id because the id has to refer 2 attributes from Bet. So using @Getter and @Setter (with lombok) is not possible. So, how can I handle this? Is even possible to have a key like this?


Solution

  • You can add a setter with two arguments:

    public void setBetID(User user, Game game) {
       this.betId = new BetID(user, game);
    }