首页 > 解决方案 > 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);你能告诉我我在做什么错吗?

标签: javajpaentitymanager

解决方案


尝试如下编码。

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为空?


推荐阅读