[jboss-user] [EJB 3.0] - Re: ejb3.0 deleting objects

Wolfgang Knauf do-not-reply at jboss.com
Mon Nov 17 08:02:38 EST 2008


Hi Ravi,

the easiest way is to define a "Cascade" attribute on your relationship annotation:
@OneToMany(mappedBy="...", cascade=CascadeType.ALL, fetch=...)

It gets more complicated if you cannot simply cascade the deletes (would be no good idea on many-to-many relationships ;-) ). In this case, you have to cleanup both sides of the relation before deleting child or parent. So, if you have an entity "Parent" and an Entity "Child" with a bidirectional "ManyToMany" relationship, and you want to remove one child from the relationship (without deleting it), you would have to do this (snippet for a SessionBean which contains a reference to the entity manager):

Child child = this.entityManager.getReference(Child.class, childId );
  |       
  | Collection<Parent> listParents = child.getParents();
  | Iterator<Parent> iteratorParents = listParents.iterator();
  | while (iteratorParents.hasNext() == true) 
  | {
  |   Parent parentForChild = iteratorParents.next();
  |   parentForChild.getChilds().remove(child);
  | }
  |   
  | this.entityManager.remove(child);
  | 

Hope this helps

As this question comes up quite often, it is maybe a good time to create a Wiki article about relationships ;-).

Wolfgang

View the original post : http://www.jboss.com/index.html?module=bb&op=viewtopic&p=4189788#4189788

Reply to the post : http://www.jboss.com/index.html?module=bb&op=posting&mode=reply&p=4189788



More information about the jboss-user mailing list