JPA:用具有相同ID的对象替换数据库中的对象

JPA: Replace object in DB by object with same id

我正在尝试根据用户所做的更改更新数据库中的一行。我将一个 Lesson 对象传递给了我的数据库管理器,现在我需要在我的数据库中更新该对象,以便它与传递的对象的属性相匹配。

我感觉有比我现在想的更好的方法。我的猜测是通过 id 获取对象,将其所有属性设置为新值,然后提交。但由于 id 参数与 changedLes.getId() 相同,感觉覆盖旧数据库条目可能更简单。但是我不知道该怎么做,也不知道这是否是正确的方法。

void update(ClubLes changedLes, int id) {
     try {
        GenericDaoJpa.openPersistency();
        Clubles les = em.find(ClubLes.class, id);
        em.getTransaction().begin();
        //setters? eg les.setName(changedLes.getName())
        em.getTransaction().commit();
        GenericDaoJpa.closePersistency();
    } catch (NoResultException e) {
        GenericDaoJpa.closePersistency();
        throw new NoResultException("Les could not be modified! try again!");
    }
}

我使用的是自动生成的密钥,所以我不确定这是否会导致问题。

要更新您需要执行的实体

em.merge(entity);
em.flush();

https://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html#merge-T-

https://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html#flush--