java - EntityManager 在 find 挂起应用程序后仍然存在
问题描述
我正在使用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
为空?
推荐阅读
- python - dicts的嵌套合并
- php - 为什么到达php页面时ajax @post为空
- ruby-on-rails - Stock_quote 版本 2.0.0
- c - 为什么我的 Makefile 每次都重新编译?
- javascript - 从 json 数据对象中的树上的第一级子级获取所有父级 ID
- python - 在python循环中对数组元素求和
- angular - 无法按预期通过路由器链接以角度呈现页面
- python - 合并两个熊猫数据框,只获取列标题
- android - 我的应用在从 google play store 下载时没有请求权限。我在清单文件中指定了位置权限
- ios - 在 Playground 上添加 iOS 资源