Hibernate: Moving Entities Between Collections

Discussion in 'Java' started by wls, Nov 13, 2007.

  1. wls

    wls Guest

    Is it possible to move an entity from one collection to another?

    I have two top level entities A and B which both have one-to-many
    references to another entity C, which happens to have its own network
    of stuff below it.

    Cascade deletes are working fine - if I delete C, it and everything
    below it goes away. Also, if I delete A or B, then it and its
    children also go away. So far so good, and I want to keep this
    cascading behavior.

    Now the interesting part.

    I want to take C, remove it from A's one-to-many collection and add it
    to B's one-to-many collection, preserving the object network under c.

    a.getChildren().remove( c );
    c.setParent(null);
    b.getChildren().add(c);
    c.setParent( b );

    I get errors like "Found two representations of same collection" the
    moment I do the add().

    I'd think this would be a trivial reassignment of some foreign keys,
    but there seems to be more to the story. Anyone know what it is?
    Does Hibernate assume remove() is a delete? The object c is not being
    orphaned.

    Thanks,
    -Walt Stoneburner,
     
    wls, Nov 13, 2007
    #1
    1. Advertisements

  2. wls

    wls Guest

    For those who stumble upon this post in the future, it turns out that
    the collections had the CASCADE_DELETE option set.

    When cascade-delete is used in conjunction with remove(), it appears
    that the object actually stays behind in the collection in a state
    that is marked for deletion [even though the object part of the ORM
    stays around]; when the object is re-added to another collection,
    Hibernate thinks there is a duplicate.

    The solution is to remove cascade-delete and handle the deletion of
    associations manually.

    See http://forum.hibernate.org/viewtopic.php?t=981282 for the answer
    to this question, along with a pretty graphical picture of the
    problem.

    -wls
     
    wls, Nov 15, 2007
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.