Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

removing all objects on many side of one-to-many relationships

 
B Nirvan
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have a classic one-to-many relation between Donor and his phones. I have mapped this using a java.util.Map as shown below.
In Phone entity

In Donor entity

The challenge I am facing is removing all the phones(many side) of the donor(one side). The code I was expecting to work is given below.

After executing the above removal code, if I again try to add an phone to the donor, I am getting a ConstraintViolationException which means that the removal code didn't work. Any ideas why the phones are not being removed from the relationship. If someone can provide a better implementation I would be very grateful.

regards,
Nirvan.
 
Tim Holloway
Saloon Keeper
Posts: 18367
56
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You probably need to commit the remove transaction before doing the add. Then again, removing from the iterator isn't necessarily going to remove from the persistence context. You probably need to do additional work. It's extra messy since you have to remove the key from the collection and delete the value from the database.

Incidentally, I believe in JPA2 they finally added a bulk removal function so that you don't have to code in a loop to do all that.
 
B Nirvan
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tim,
Basically I was trying to update the phones with the values entered by the user. First I thought it would be possible to simply remove all entries from the map and add the new entries. But as you said, it may require either a commit (which I cannot do since I am in middle of a transaction) or perhaps flush (which would mean additional database hit). So I changed the way I edit phones by simply locating the correct phone record from the phones map and updating its values. For that I used the simple code given below.

Surprisingly, the above code does not update values in the database ! Can it be a problem with hibernate, or is there some mistake in my code.

regards,
Nirvan.
 
Tim Holloway
Saloon Keeper
Posts: 18367
56
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's hard to say. If you've detached the objects, then you'd have to merge them back to get the update to take, but if they're still attached and you haven't attempted to modify the primary key, I can't think of anything. Maybe the logs have something to say.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic