2 Replies Latest reply on Nov 18, 2008 2:20 AM by mravikrish

    ejb3.0 deleting objects

    mravikrish



      Hello,

      I am Ravi, I am having problem with deleting objects which are in relationships(one-many,many-many). ex : if i delete project object. all its associated objects should be deleted . my project object is associated to 3 objects(projectstatus,bid...).


      any help appreciated.

      Thank u
      Ravi

        • 1. Re: ejb3.0 deleting objects
          wolfgangknauf

          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

          • 2. Re: ejb3.0 deleting objects
            mravikrish

            thank you Wolfgang Knauf