I use Jakarta EE, Hibernate 6.
There are two models:
- Gamer
@Entity
@Table(name = "GAMER")
public class Gamer {
@Id
@Column(name ="GAMER_ID", columnDefiniton = "BINARY(16)")
private UUID id;
@Column(name = "NAME", nullable = false, unique = true)
private String name;
public Gamer() {}
public void generateID() {
id = UUID.randomUUID();
}
//getters and setters
}
- Game
@Entity
@Table(name = "GAME")
public class Game {
@Id
@Column(name = "GAME_ID", columnDefinition = "BINARY(16)")
private UUID id;
@OneToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private Gamer gamerOne;
@OneToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private Gamer gamerTwo;
@OneToOne
private Gamer winner;
public Game() {}
//getters and setters
}
I create a game, I put 2 players in it, the game is not stored immediately in the database (H2Database). Only at the end of the game you need to save the game to the database. If the players in the game fields store those that are not in the database, then the saving is successful. If I try to save a game with players that are already exist in the database (by the name of the player - each is unique), then an exception is thrown (a unique value). Is it possible to use cascading tables to save players in the database if they are not in the database and return a player with his id from the database if he exists? Is this possible without using Spring?
I put players like this:
Gamer one = new Gamer();
one.generateId();
one.setName("Jon");
Gamer two = new Gamer();
two.generateId();
two.setName("Bob");
Game game = new Game();
game.setGamerOne(one);
game.setGamerTwo(two);
game.setWinner(one);
session.persist(game);
//or
session.merge(game);
//or
session.save(game);
//or
session.saveOrUpdate(game);