views:

535

answers:

1

In my database I've got Users and UserGroups which have a many-to-many relation. The User has a set of UserGroup, the UserGroup domain object does not see the User.

<class name="User" table="UserTable">
    <set name="UserGroup" cascade="save-update" access="field.pascalcase-underscore" table="User2UserGroup">
        <key column="User_Id" />
        <many-to-many class="UserGroup" column="UserGroup_Id" />
    </set>
    ...

What I'm trying to achieve is the nhibernate deleting the correlation from the juction table when I delete either a User or a User Group. Additionally User and Group are child objects of, hmm, let's call it a Domain. Domain does cascade="all-delete-orphans", so when a Domain gets deleted it cascade-deletes all its Users and UserGroups.

Back to the User<->UserGroup relation: If I understand correctly I can't use any form of cascade that involves delete as I just want to delete the association between two objects and not the related object itself. (A group shall not vanish, even if it's an orphan. And a User without a group is a valid thing in my world - he just has no rights to do anything at all.)

Do I need to look at events / interceptors? Or can I do what I want to achieve by controlling the mapping?

+1  A: 

If you are using a database that supports it can you not set the cascade on the database itself in the form of a Foreign Key constraint?

Michael Gattuso
That might work, but I suspect it might create a lot of trouble in the NHibernate cache.
froh42
AFAIK there is no issue with using the cascade delete on the database with NHibernate. For a discussion on using solving this with Event Listeners (in NHibernate 2.1) check out this document:http://elegantcode.com/2009/07/19/nhibernate-2-1-and-collection-event-listeners/
Michael Gattuso
Michael, thanks for all the input and the link. As I already have looked into the directon of event listeners (in fact, I've already proceeded as far as registering a do-nothing event listerner in my application) this is the direction I'll proceed. Even if the database is able to delete things behind the scenes (which might even be a lot faster) I prefer not to do so as I want to keep everything in the same layer. From the pre-nhibernate-2 roots of my application I still have an unhealthy amount of SQL instead of executable HQL.
froh42