【问题标题】:Update database when some entries were removed JPA删除某些条目时更新数据库 JPA
【发布时间】:2015-04-07 01:06:05
【问题描述】:

我正在我的项目的服务器端开发一个逻辑,它将更新数据库中的实体。但是这个实体引用了另一个实体的列表。

所以,例如我有一个像这样的实体Test

    @Entity
    public class Test {

        @Id
        @Column(name = "idTest", nullable = false)
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
        private String name;

        @OneToMany(mappedBy = "idTest", targetEntity = Test2.class, fetch = FetchType.LAZY)
        private Collection<Test2> test2Collection;
    }

其中引用了Test2 Entity。

@Entity
public class Test2 {

    @Id
    @Column(name = "idTest2", nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String field1;
    private String field2;

    @ManyToOne
    @JoinColumn(name = "idTest", referencedColumnName = "idTest")
    private Test idTest;
}

就我而言,我正在更新集合 test2CollectionTest 条目,最终我将删除其中的一些 Test2 条目。

来自EntityManager 的简单merge 方法在我调用它传递新的更新Test 条目时没有检测到某些条目已被删除。

我正在考虑通过在 Test 条目之间进行差异来跟踪从 test2Collection 中删除的条目,然后再使用要更新的新 Test 条目更新数据库。

但我不确定这是唯一(也是最好的)方法。其他人有其他想法吗?

【问题讨论】:

  • 您不只需要 OneToMany 上的“cascade = CascadeType.ALL”吗?

标签: java spring hibernate jpa entitymanager


【解决方案1】:

在你的关系中,你必须添加orphanRemoval,那么如果你移除集合中的一个元素并持久化Test,那么集合上被删除的元素将自动从Test2表中删除。

@OneToMany(orphanRemoval = true, mappedBy = "idTest", targetEntity = Test2.class, fetch = FetchType.LAZY)
    private Collection<Test2> test2Collection;

【讨论】:

  • 谢谢!这种方法比我想象的要好得多!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-15
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 2019-12-15
  • 2021-08-30
  • 2014-07-31
相关资源
最近更新 更多