【问题标题】:Hibernate collection retains reference to deleted entityHibernate 集合保留对已删除实体的引用
【发布时间】:2017-03-08 22:13:43
【问题描述】:

我们使用 spring-data hibernate 作为我们的数据库访问的 ORM。我的实体设置如下:

class E1 {
    @Column(name = "e1_id")
    private BigDecimal e1_id;   

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "e1", orphanRemoval=true, fetch = FetchType.EAGER)
    @Fetch(value = FetchMode.SUBSELECT)
    private Collection<E2> e2List;
}

class E2 {
    @Column(name = "e2_id")
    private BigDecimal e2_id;

    @JoinColumn(name = "e1_id", referencedColumnName = "e1_id")
    @ManyToOne
    private E1 e1;
}

现在我尝试以下方法: 创建一个新的 E1 并使用 spring JPA 存储库保存,无需显式的 spring 事务。

E1 detachedE1 = e1Repo.save(e1);

e1 有一个非空的 e2 集合。

我从 e1 中删除 e2 实体,然后将 e1 保存在 spring 事务中。

然后,我尝试使用 detachedE1 如下:

   detachedE1.setE2Collection(Collections.emptyList())
   e1Repo.save(detachedE1)

上面的代码报错了,报错基本是说:

springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find entity.E2 with id 1.00

我的问题是,JPA 如何保留对已删除集合的引用。我将 E2 集合设置为空列表。而且我还验证了 e1Repo.find(detachedE1.e1_id) 返回的实体有一个空集合。

提前感谢任何回复/指点!

只是想添加我们使用hibernate hibernate-entitymanager-4.3.8.Final.jar

【问题讨论】:

    标签: java hibernate orm spring-data-jpa


    【解决方案1】:

    所以在使用调试器挖掘休眠代码后,我终于想通了。分离实体的集合确实是一个 PersistentBag,这应该不足为奇。 但是persistent bag维护了一个snapShot,当我将collection设置为emptyList时并没有清空。

    为了验证我的最终理论,我添加了以下内容:

    ((PersistentCollection)e1.getE2Collection()).setSnapshot(null, null, null);
    

    在此之后,休眠持久上下文能够成功合并分离的实体,并将 E2 集合设置为空列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-04
      • 1970-01-01
      • 2021-05-09
      • 2013-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-29
      相关资源
      最近更新 更多