【问题标题】:JPA deleting inverse relationshipJPA删除反向关系
【发布时间】:2011-12-06 07:57:22
【问题描述】:

我一直在尝试删除 JPA 实体上的反向关系,但是效果不佳。我现在正在尝试将 ManyToOne 属性设置为 null,然后使用 entityManager 的 merge 方法保存它。 ManyToOne 关系用 cascade all 属性标记,但是在数据库中,外键没有被删除。我该怎么做?非常感谢。

【问题讨论】:

    标签: jpa-2.0


    【解决方案1】:

    使用有问题的代码更容易找出您的意思。但无论如何我都会尝试:

    @Entity
    public class AEntity {
        @GeneratedValue (strategy = GenerationType.SEQUENCE)
        @Id int id;
    
        //Having some cascade here doesn't matter for our case
        //because we now do not cascade anything, we just set this field to
        //null. Cascade=REMOVE is about never meaningful (and never fully
        //fully portable) in ManyToOne side:
        //just think what happens to other AEntity instances that refer to 
        //same BEntity.
        @ManyToOne
        BEntity bEntity;
    
        public void setbEntity(BEntity bEntity) {
            this.bEntity = bEntity;
        }
    }
    
    public class BEntity {
        @GeneratedValue(strategy = GenerationType.SEQUENCE)
        @Id int id;
    }
    

    一开始我们有以下数据:
    AEntity(id=1,bEntity_id=2)
    BEntity(id=2)

    然后删除a和b之间的连接:

    AEntity oldDirty = em.find(AEntity.class, 1);
    //modify A somewhere else in code
    oldDirty.setbEntity(null);
    //and bring changes in:
    em.merge(oldDirty);
    

    之后我们有:
    AEntity(id=1,bEntity_id=null)
    BEntity(id=2)

    如果 BEntity 也有包含 AEntity 实体的集合(也就是说双向关系),那么你也必须从那里删除 A,因为你必须自己关心关系。 OneToMany 一侧是可以进行级联删除的一侧。

    【讨论】:

      【解决方案2】:

      检查两端关系的级联类型。例如,如果您想在删除主实体时删除所有关联实体,则注解应如下所示:@ManyToOne(cascade={CascadeType.REMOVE}),反之为@OneToMany(cascade={CascadeType.REMOVE})

      【讨论】:

      • 在 ManyToOne 端使用 REMOVE 时,您希望发生什么?在最好的情况下,当然可以有一些特定于供应商的有意义的功能。
      猜你喜欢
      • 2011-03-29
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      • 2017-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多