我使用JPA将一些数据保存到表中。在坚持之前,我检查该记录是否存在。
public boolean save(Student student) {
//below em is an EntityManager object
Student record = em.find(Student.class, student.getId());
if (record != null)
return false;
em.persist(student);
return true;
}
此方法卡在 em.persist(student);
上,您能告诉我我做错了什么吗?
最佳答案
尝试按如下方式编写代码。
public Student save(Student entry) {
if (entry.getId() == null) {
// If you don't have id, it's new, so persist
em.persist(entry);
} else {
// If you have id, it's an update of the existing entry, so merge.
entry= em.merge(entry);
}
return entry;
}
<小时/>
更新
现在才意识到。
您显然只想保存新条目,对吧?
换句话说,您不想保存/更新现有条目,是吗?
public boolean save(Student student) {
Student record = em.find(Student.class, student.getId());
if (record != null)
return false;
em.persist(student); // ★ Is it ok, if you pass entry with already set id?
return true;
}
您是否尝试将 student.id
设置为 null?
关于java - find 挂起应用程序后 EntityManager 仍保留,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57782919/