Hibernate @OneToMany - cascade delete problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Paks
    New Member
    • Dec 2006
    • 13

    Hibernate @OneToMany - cascade delete problem

    Hi there,
    I'm developing a web project based game and have run into a problem and gotten confused by the annotations in the Hibernate framework.

    I'm trying to have both the relation and child deleted while updating the parent object with a removed child.
    And I've only managed to make the relationship table entry to be deleted and not the child itself.
    I could delete the child manually but that just seems like bad coding to me. Especially when I've managed to do this with earlier versions of hibernate, without the annotations part.

    I've spent a lot of time on this trying to figure it out, searching the web and more specific a lot of forums for answers.
    But I feel completely stumped on how to fix this.

    The parent code:
    Code:
    public class Parent implements Serializable{[INDENT]
    @OneToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "parents_children", joinColumns =  @JoinColumn(name = "parent_id"), inverseJoinColumns = @JoinColumn(name = "child_id"))
    private Collection<Child> children;	
    [/INDENT]
        
    // blablabla... etc code
    }
    The part of the method containing the remove functionality:
    Code:
    parent.getChildren().remove(childToRemove);  // getChildren returns a Collection<Child>
    session.saveOrUpdate(parent);
    What I want to do is to get a parent connected to it's child so when you updated a parent where you have deleted a child from.
    Both the relation in the relation table will be removed as well as the child itself.

    I would really prefer some help, please.

    -- Paks
  • Paks
    New Member
    • Dec 2006
    • 13

    #2
    Apparently we just had to add one row to the annotation:
    Code:
    @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
    So that it looked like this:
    Code:
    @OneToMany(cascade = CascadeType.ALL)
    @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
    @JoinTable(name = "parents_children", joinColumns = @JoinColumn(name = "parent_id"), inverseJoinColumns = @JoinColumn(name = "child_id"))
    private Collection<Child> children;
    Sometimes there's the most simple solution to the most annoying problem :P

    Cheers,
    Paks

    Comment

    Working...