2011-10-12 77 views
0

我一直在试图删除JPA实体上的反向关系,但是这一直没有奏效。我现在正在尝试将ManyToOne属性设置为null,然后使用entityManager的合并方法保存它。 ManyToOne关系用cascade all属性标记,但是在dataBase中不会删除外键。我应该怎么做?非常感谢。JPA删除反比关系

回答

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)

然后删除之间的连接和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(ⅰ d = 2)

如果BEntity还建立包含AEntity实体(这么说的双向关系),那么你必须也从那里删除,因为你要不断关心自己的关系。 OneToMany方面是可以从中级联移除的方法。

0

检查两端关系的级联类型。举例来说,如果你想,当你删除的主要实体,删除所有相关实体,注释应该是这样的:@ManyToOne(cascade={CascadeType.REMOVE}),并在逆@OneToMany(cascade={CascadeType.REMOVE})

+0

你想使用删除多对一的一面,当要发生的事情?在最好的情况下,当然可以有一些供应商特定的有意义的功能。 –