0

I use Jakarta EE, Hibernate 6.

There are two models:

  1. 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
}
  1. 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);
dKopyshov
  • 1
  • 2
  • 1
    Related: [JPA EntityManager: Why use persist() over merge()?](https://stackoverflow.com/q/1069992) Though what you should actually take from that is that using `merge()` instead of `persist()` will probably do what you want. – John Bollinger Aug 17 '23 at 12:20
  • How are you putting 2 players in it exactly? If they aren't read from the database, I'd hope you are setting the ID and not just their name - you defined the UUID id as uniquely identifying gamer instances, so that is all that JPA will use to determine if it is an existing instance or a new one. If you are only using the gamer name, you'll have to search the DB to get the existing instance (if it exists) and use that in your game instance. – Chris Aug 17 '23 at 16:15
  • I updated my post, u can see that – dKopyshov Aug 19 '23 at 19:26

0 Answers0