-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: auto delete many2many join records
PostPosted: Thu Nov 29, 2007 1:04 pm 
Newbie

Joined: Tue Sep 19, 2006 4:48 pm
Posts: 10
Hibernate Version 3.2.5.ga w\ JPA

I have a ManyToMany association between 2 entities A & B.

When I associate an A to a B a record is automatically created in the the join table.

When I unassociate an A from a B the record is automatically removed from the the join table.

This is all fine. However, if I just try to delete the A instance I get a constraint violation.

If I setup cascadeType to REMOVE then the associated instances of B are also removed, which is not what I want.

Is there a way to cascade/automatically delete just the join records?


Top
 Profile  
 
 Post subject:
PostPosted: Fri Nov 30, 2007 6:07 pm 
Newbie

Joined: Tue Sep 19, 2006 4:48 pm
Posts: 10
OK, I consider this more of a workaround, but it gets the job done.

I have created an event listener method that will remove all the m2m associated objects prior to delete. Doing it this way ensures that this will always get fired.

The remove method clears the association on both sides.
The removeAll method handles the whole collection.
The preRemove method triggers the whole thing.

Code:

   public void removeChannel(Channel channel) {
      if (channel == null)
         return;
      getChannels().remove(channel);
      channel.getOfferAvailabilities().remove(this);
   }

   public void removeAllChannels() {
      List<Channel> remove = new ArrayList<Channel>();
      remove.addAll(getChannels());
      for (Channel channel : remove) {
         removeChannel(channel);
      }
   }

   @PreRemove
   public void preRemove() {
      removeAllChannels();
   }



Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.