2011-10-27 99 views
5

在Google App引擎java jpa中有一对多关系,我该如何删除子元素。 例如谷歌应用引擎java jpa一对多删除

Class Parent{ 
    // key defined here 

    @OneToMany(cascade=CascadeType.ALL, mappedBy="parent") 
    private List<Child> childs = null; 
. 
. 
. 
} 

Class child{ 
//key defined here too 
@ManyToOne 
private Parent parent; 
. 
. 
. 
} 

我创建

Parent parent=new Parent() 
parent.getChilds().add(new Child(1)); 
parent.getChilds().add(new Child(2)); 
//save parent 
. 
. 

,现在我想删除这两个孩子的1和2,并添加一个新的子3

Parent p=//getParent 
p.setChilds(new ArrayList<Child>())//remove all older childs 
parent.getChilds().add(new Child(3));//adding new child 3 
. 
. 

但是,当我再次读取该相同的父母我有所有3个孩子,但不仅孩子3.

任何人都可以请guid e我。

感谢, Ramesh.V

回答

0

也许做

parent.getChilds().clear(); 

,因为可以节省删除并重新创建一个列表,并可能有周围的一些GAE问题工作的额外好处。 PS。 “孩子”的复数是“孩子”!

+0

对不起,没有工作......但清除或设置一个新的空对象都有一些在工作中没有区别...... –

0

你可以尝试从拥有的一方删除关系 - 在这种情况下,Child#父母。因此,对于父集合中的每个子元素,请尝试:移除子元素或将父元素设置为null。就像:

Parent p = //getParent 
List<Child> children = p.getChildren(); 
for (Child c : children) { 
    c.setParent(null); 
} 

children.clear(); 
children.add(new Child(3));