【问题标题】:EntityManager persist after find hangs the applicationEntityManager 在 find 挂起应用程序后仍然存在
【发布时间】:2020-01-07 00:34:55
【问题描述】:

我正在使用 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);上,你能告诉我我做错了什么吗。

【问题讨论】:

  • 在您的问题中包含实体代码

标签: java jpa entitymanager


【解决方案1】:

尝试编写如下代码。

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

【讨论】:

  • 当我在 find() 之后立即 persist() 时,锁没有任何问题。由于我的代码挂在 em.persist()
  • 我不知道锁有没有问题...更新了答案。
  • 是的,我不想更新。只创建新记录。是的,对象的 ID 已经设置。但仍然坚持坚持
  • 您是否尝试将 student.id 设置为空?ヾ(๑╹◡╹)ノ"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-08
  • 1970-01-01
  • 1970-01-01
  • 2021-09-11
  • 2015-07-24
相关资源
最近更新 更多