我正在使用 Servlets 和 Hibernate 创建一个 CRUD 应用程序。
当我尝试使用 save() 保存新实体时,Hibernate 执行 SQL 更新查询而不是插入。该实体已经包含生成的 Id (UUID),据我了解,它在数据库(内存中的 h2)中搜索该实体,但没有找到。如果已经生成了 id,如何在数据库中正确保存实体。
@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();
}
据我了解,您希望在不让 Hibernate 为您生成标识符的情况下将实体保存在数据库中。要完成它,您可以使用以下代码:
如果具有 id 的实体已经存在于数据库中并且应该更新 - 请使用:
session.merge(myEntity); // myEntity contains the id
如果它是一个新实体并且应该被插入 - 请使用:
UUUID id = UUID.randomUUID(); // new id will be generated
myEntity.setId(id);
session.persist(myEntity);