【问题标题】:Hibernate JPA value removing OneToMany relationHibernate JPA 值删除 OneToMany 关系
【发布时间】:2013-01-16 12:12:14
【问题描述】:

我有两个表,其中存在 OneToMany、MnatToOne 关系。

当我将 AlarmnotifyEmailEntity 的实例添加到 alarmnotifyEmailEntityList 对象并更新 AlarmnotifyEmailConfEntity 的实例时,值将正确保存到数据库中。

但删除alarmnotifyEmailEntityList 的一项时我不能做同样的事情。 我确信该值已从 alarmnotifyEmailEntityList 中删除,但它并未将这些更改反映到数据库中

    @Entity(name ="alarmnotify_email_conf")
    @Table(name = "alarmnotify_email_conf")
    public class AlarmnotifyEmailConfEntity implements Serializable {

    @OneToMany(mappedBy = "alarmnotifyEmailConfRef",cascade=CascadeType.ALL)
        private List<AlarmnotifyEmailEntity> alarmnotifyEmailEntityList;

    }//end of Class

    @Entity (name ="alarmnotify_email")
    @Table(name = "alarmnotify_email")
    public class AlarmnotifyEmailEntity implements Serializable {
     @JoinColumn(name = "alarmnotify_email_conf_ref", referencedColumnName = "id")
        @ManyToOne
        private AlarmnotifyEmailConfEntity alarmnotifyEmailConfRef;
    }end of Class

我只是调用以下语句进行更新。

JPAManager.getJPAManagerInstance().update(alarmnotifyemailconf);

 public Object update(Object o) {

  try {
     tx.begin();
     EntityManager em = getEntityManager();          
     System.out.println("updating object:" + o);
     o = em.merge(o);
     em.close();
     tx.commit();
     System.out.println("closed and commited merge operation");
     return o;
  }
  catch (Exception e) {
     e.printStackTrace();
  }
  return o;

}

【问题讨论】:

  • 您是否尝试将 cascade=CascadeType.ALL 添加到关系的 @ManyToOne 一侧?
  • 如果@ManyToOne 有CascadeType.All,它会触发删除AlarmnotifyEmailConfEntity 实例。但我不想要这个操作。

标签: java hibernate jpa


【解决方案1】:

根据我的经验,级联仅适用于相同的操作。如果我们保存父级,那么子级也将使用更新保存相同的案例。但我认为当你想删除其中一个孩子时,我们必须使用实体管理器显式删除,并且不能仅仅合并父级,并且期望将级联删除到子级。

【讨论】:

    【解决方案2】:

    我在jpa removing child from collection找到了答案。 结果添加 orphanRemoval=true 解决了问题。

    @Entity(name ="alarmnotify_email_conf") @Table(name = "alarmnotify_email_conf") 公共类 AlarmnotifyEmailConfEntity 实现 Serializable {

    @OneToMany(mappedBy = "alarmnotifyEmailConfRef",cascade=CascadeType.ALL ,orphanRemoval=true) 私有列表 alarmnotifyEmailEntityList;

    }//end of Class
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-16
      • 1970-01-01
      • 1970-01-01
      • 2019-01-12
      • 2016-04-21
      • 2021-12-21
      • 2017-06-23
      • 1970-01-01
      相关资源
      最近更新 更多