I am creating a CRUD application using Servlets and Hibernate.
When I try to save a new entity using save(), then Hibernate executes the SQL Update query and not Insert. The entity already contains the generated Id (UUID) and as I understand it, it searches for this entity in the database (h2 in-memory) and does not find it. How to properly save an entity in the database if the id has already been generated.
@Entity
@Table(name = "MATCH")
public class Match implements Serializable {
@Id
@Column(name = "MATCH_ID")
private UUID id;
@ManyToOne
private Player playerOne;
@ManyToOne
private Player playerTwo;
@ManyToOne
private Player winner;
@Transient
private int[] score = new int[2];
public Match() {
}
//getters and setters
}
public void executePost(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException {
Transaction transaction = null;
try (Session session = DBHandler.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
UUID MatchUuid = UUID.fromString(servletRequest.getParameter("match-uuid"));
currentMatchService = CurrentMatchService.getInstance(); //service stores current matches in the app's memory
currentMatch = currentMatchService.getMatch(MatchUuid);
currentMatch.setWinner(currentMatch.getPlayerOne()); //player One set like winner just for test
session.save(currentMatch);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}