I have been trying to delete the inverse relationship on a JPA entity, however this have not been working well. What I'm trying right now is to set the ManyToOne property to null and then saving it using the entityManager's merge method. The ManyToOne relationshi开发者_开发技巧p is marked with the cascade all property, however in the dataBase the foreign key is not removed. How should I do this?. Thanks a lot.
It would be easier to find out what you mean, with code in question. But I will try anyway:
@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;
}
In the beginning we have following data:
AEntity(id=1,bEntity_id=2)
BEntity(id=2)
Then removing connection between a and b:
AEntity oldDirty = em.find(AEntity.class, 1);
//modify A somewhere else in code
oldDirty.setbEntity(null);
//and bring changes in:
em.merge(oldDirty);
Afterwards we have:
AEntity(id=1,bEntity_id=null)
BEntity(id=2)
If BEntity also have set that contains AEntity entities (so to say bidirectional relationship), then you have to remove A from there as well, because you have to keep care about relationship by yourself. OneToMany side is one where it can make sense to cascade removal from.
Check the cascade type of the relationship on both ends. For instance, if you want to delete all the associated entities when you delete the main entity, the annotation should look like this: @ManyToOne(cascade={CascadeType.REMOVE})
, and on the inverse @OneToMany(cascade={CascadeType.REMOVE})
精彩评论