0

I am building a REST API with SpringBoot and I am using Lombok. I have 2 entity classes, they have a many to many relationship and I am trying to create a new Game object in a service class, but when I try to do this I don't know the id as it is autogenerated, so how can I create a Game object without the 'gameId' field? so I can then save it to the database, where it will automatically generate that id?

@Entity
@Table(name = "game")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Game {

    private @Id
    @GeneratedValue
    Long gameId;

    //One game can have many players and one player can have many games so many-to-many relationship.
    @ManyToMany
    private Set<User> User;

    private Boolean blueIsWinner;

    private String yesIndeed;

}

GameService:

Set<User> users = new HashSet<>();
        users.add(currentUser);
        users.add(opponentUser);
        Game game = new Game(users, true, "yesIndeed");
        Game savedGame = gameRepository.save(game);

As you can see, in this service I am trying to construct the Game object so that it can be saved. I add the user objects to the set. There is an error when I try to construct the game object obviously, is there any way to do this using Lombok?

Thanks

Tim Hudson
  • 63
  • 1
  • 2
  • 10

1 Answers1

1

This is currently not possible with Lombok, but there is nothing stopping you from creating the constructor on your own:

@Entity
@Table(name = "game")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Game {

    private @Id
    @GeneratedValue
    Long gameId;

    //One game can have many players and one player can have many games so many-to-many relationship.
    @ManyToMany
    private Set<User> User;

    private Boolean blueIsWinner;

    private String yesIndeed;

    public Game(Set<User> user, Boolean blueIsWinner, String yesIndeed) {
        User = user;
        this.blueIsWinner = blueIsWinner;
        this.yesIndeed = yesIndeed;
    }
}
João Dias
  • 16,277
  • 6
  • 33
  • 45