Jonathan
Jonathan

Reputation:

Many-to-Many Cascading Delete

I have defined a many to many relationship between two classes. Event and Person (defined in a separate database table person_event). Now, suppose I want to delete a person, so all its related associations with events must also get deleted from the person_event table. In other words, I want cascade ON DELETE.

Let's consider a scenario:

Now, suppose I delete event 1 using Hibernate.delete(), then not only does it delete event1, and association person_event1-4, but also the person4!

The problem is person4 is referenced by another tables and it throws an Foreign Constraint Exception... How I could configure NHibernate to delete just the Event and associations person_event?

Upvotes: 1

Views: 870

Answers (2)

Zuber
Zuber

Reputation: 577

I think if you set the Cascade setting to none on the many to many map, you should be able to get what you want.

It will only delete entries pertaining to event, but not cascade the delete effect to Person.

Upvotes: 2

Jason S
Jason S

Reputation: 189626

I'm not that experienced in Hibernate, but I think you want to remove your event from any person associated with it, through the person objects in question, before you call Hibernate.delete().

This gets into object lifetime issues which I think you'd want to think through very carefully. For instance, if event1 is associated with person1 and person2 and person4, and you delete person1, you probably would not want event1 to be automatically deleted.

Upvotes: 0

Related Questions