0

Suppose I have 2 Java objects: Parent and Child. The relationship between them is Child -> Parent = many-to-one, i.e. a number of Child objects can be associated with the same Parent.

A Child object is holding a reference to its Parent meanwhile Parent object has no field to address its Children.

In Hibernate that results in having a many-to-one element in Child mapping; Parent's mapping doesn't contain one-to-many entry since there is no need for a Parent object to have a collection field to reference all its Child objects.

Now, when Parent is deleted Oracle throws an exception that the entity cannot be deleted while there are child entities referencing it.

With this object model, is there a way to casacadely delete all Child objects that belong to Parent object when the latter gets deleted?

preeze
  • 1,061
  • 1
  • 12
  • 18

2 Answers2

1

1> make bi directional mapping to Child <--> parent. mention cascade delete.

2> you know who are the childs object of this parent, first delete all childs of this parent and then try to delete parent.

EDIT:

check this example link

Hibernate Bidirectional Example

NPKR
  • 5,368
  • 4
  • 31
  • 48
  • The thing is I don't want to introduce a new "children" field to Parent object simply for the sake of cascade deletion. – preeze May 24 '13 at 11:48
  • to make bi directional relation ship , parent doesn't reuired child refference. – NPKR May 24 '13 at 11:52
  • I have checked that exmaple before posting this question.As far as I can see in that example Team does define "players" field. – preeze May 24 '13 at 12:00
1

Class Parent

import java.util.Set;  

    import javax.persistence.*;  

    @Entity  
    @Table(name = "Parent")  
    public class Parent{  

        @Id  
        @GeneratedValue  
        private Integer id;  

        private String name;  

        @OneToMany(mappedBy="Child", cascade=CascadeType.ALL)  
        private Set<Child> child;  
}

consider second class called child

import javax.persistence.*;

@Entity  
@Table(name = "Child")  
public class Child{  

    @Id  
    @GeneratedValue  
    private Integer id;  

    private String lastname;  

    @ManyToOne  
    @JoinColumn(name = "id")  
    private Parent parent;  
}

just make changes in your POJO's accordingly it will not throw exception

shreyansh jogi
  • 2,082
  • 12
  • 20
  • I might have been not clear to state that Parent must not contain a field "Set children". But in your example it actually does have it so this solution is not 100% what I was looking for. – preeze May 24 '13 at 13:22