0

I have a scenario where I need to Delete a parent entity and In doing so I need to nullify the references associated with the parent.

e.g. I have two tables/entities Person and Address. Person is the parent and Address is the child (One to Many). Now when I delete Person I need to nullify the person references in Address table.

Do we have any pre-defined annotations to do this Job.

Any help/suggestion is highly appreciated.

Thanks.

user1679893
  • 19
  • 1
  • 3
  • 1
    in JPA, you **have** to do this manually. I have strong doubts that Hibernate can do it automagically. Still curious. – kostja Apr 09 '13 at 12:42

2 Answers2

0

The simplest way i see is to refresh the child entities after removal. As your relationship is bi-directional you can otherwise manage this automatically using a @PreRemove method on the parent (set all childs' parent reference to null).

IMHO the word transient is misused here, transient means that the property will not be persisted, removed reference should be more appropriate.

Gab
  • 7,869
  • 4
  • 37
  • 68
0

You have to do it manually:

@Entity
public class Person {
    ...
    @OneToMany(mappedBy="person")
    public List<Address> addresses;  
    ...
}

@Entity
public class Address {
    ...
    @ManyToOne
    public Person person;
    ...
}

for (Address address: person.addresses) {
    address.person = null;  
}
session.delete(person);
lunr
  • 5,159
  • 4
  • 31
  • 47