reset password
Author Message
tonyg
Posts: 11
Posted 20:07 Feb 09, 2015 |

Suppose that I retrieve 2 collections, and an element from one of the collections from a database. I want to swap the element from one collection into the other. This would mean having an element object, and removing it from the first collection, then adding it to the second collection. However, merging the collection that had the item removed fails--the element is still present in the collection. Why does this happen? Is there an alternative for swapping an element from one collection to another?

cysun
Posts: 2935
Posted 21:10 Feb 09, 2015 |

It sounds like this should work. Does the element has a reference to the parent object (i.e bidirectional association)?

tonyg
Posts: 11
Posted 21:16 Feb 09, 2015 |

No, it's unidirectional. Would a bidirectional association allow this to work?

cysun
Posts: 2935
Posted 21:18 Feb 09, 2015 |

Are both collections owned by the same parent object? Are they both unidirectional? Are they one-to-many or many-to-many?

tonyg
Posts: 11
Posted 21:25 Feb 09, 2015 |
cysun wrote:

Are both collections owned by the same parent object? Are they both unidirectional? Are they one-to-many or many-to-many?

No, the collections have different parents. Both are unidirectional (one-to-many).

cysun
Posts: 2935
Posted 21:38 Feb 09, 2015 |

A unidirectional @OneToMany is not recommended (see Section 2.2.5.3.1.1 and 2.2.5.3.1.2 of Hibernate Annotations). I'm not sure about the reason.

The recommended way is to make it either bidirectional or unidirectional on the @ManyToOne side, and in both cases the @ManyToOne side being the owning side. With that changing the reference in the element should do the trick.