When to use inverse=false on NHibernate / Hibernate OneToMany relationships? - nhibernate

I have been trying to get to grips with Hibernate's inverse attribute, and it seems to be just one of those things that is conceptually difficult.
The gist that I get is that when you have a parent entity (e.g. Parent) that has a collection of Child objects using a one-to-many mapping, setting inverse=true on the mapping tells Hibernate that 'the other side (the Child) has responsibility to update itself to maintain the foreign key reference in its table'.
Doing this appears to have 2 benefits when it comes to adding Children to the collection in your code, and then saving the Parent (with cascade-all set): you save an unneccessary hit on the database (because without inverse set, Hibernate thinks it has two places to update the FK relationship), and according to the official docs:
If the column of a
association is declared
NOT NULL, NHibernate may cause
constraint violations when it creates
or updates the association. To prevent
this problem, you must use a
bidirectional association with the
many valued end (the set or bag)
marked as inverse="true".
This all seems to make sense so far. What I don't get is this: when would you NOT want to use inverse=true on a one-to-many relationship?

As Matthieu says, the only case where you wouldn't want to set inverse = true is where it does not make sense for the child to be responsible for updating itself, such as in the case where the child has no knowledge of its parent.
Lets try a real world, and not at all contrived example:
<class name="SpyMaster" table="SpyMaster" lazy="true">
<id name="Id">
<generator class="identity"/>
</id>
<property name="Name"/>
<set name="Spies" table="Spy" cascade="save-update">
<key column="SpyMasterId"/>
<one-to-many class="Spy"/>
</set>
</class>
<class name="Spy" table="Spy" lazy="true">
<id name="Id">
<generator class="identity"/>
</id>
<property name="Name"/>
</class>
Spymasters can have spies, but spies never know who their spymaster is, because we have not included the many-to-one relationship in the spy class. Also (conveniently) a spy may turn rogue and so does not need to be associated with a spymaster. We can create entities as follows:
var sm = new SpyMaster
{
Name = "Head of Operation Treadstone"
};
sm.Spies.Add(new Spy
{
Name = "Bourne",
//SpyMaster = sm // Can't do this
});
session.Save(sm);
In such a case you would set the FK column to be nullable because the act of saving sm would insert into the SpyMaster table and the Spy table, and only after that would it then update the Spy table to set the FK. In this case, if we were to set inverse = true, the FK would never get updated.

Despite of the high-voted accepted answer, I have another answer to that.
Consider a class diagram with these relations:
Parent => list of Items
Item => Parent
Nobody ever said, that the Item => Parent relation is redundant to the Parent => Items relation. An Item could reference any Parent.
But in your application, you know that the relations are redundant. You know that the relations don't need to be stored separately in the database. So you decide to store it in a single foreign key, pointing from the Item to the Parent. This minimal information is enough to build up the list and the reference back.
All you need to do to map this with NH is:
use the same foreign key for both relations
tell NH that one (the list) is redundant to the other and could be ignored when storing the object. (That is what NH actually does with inverse="true")
These are the thoughts which are relevant for inverse. Nothing else. It is not a choice, there is only one way of correct mapping.
The Spy Problem:
It is a completely different discussion if you want to support a reference from the Item to the Parent. This is up to your business model, NH doesn't take any decisions in this. If one of the relations is missing, there is of course no redundancy and no use of inverse.
Misuse: If you use inverse="true" on a list which doesn't have any redundancy in memory, it just doesn't get stored. If you don't specify the inverse="true" if it should be there, NH may store the redundant information twice.

If you want to have an unidirectional association i.e. that the children can't navigate to the Parent. If so, you FK column should be NULLABLE because the children will be saved before the parent.

Related

Storing an ordered child collection in NHibernate

I'm having trouble getting my head around the way I should implement an ordered child relationship with NH.
In the code world, I have:
class Parent
{
public Guid Id;
public IList<Child> Children;
}
class Child
{
public Guid Id;
public Parent Parent;
}
A Parent has a list of Child[ren] with an order. In reality, the Children collection will contain unique Childs which will be enforced by other code (i.e. it will never be possible to add the same child to the collection twice - so i dont really care if the NH collection enforces this)
How should I implement the mappings for both classes?
From my understanding:
Bags have no order, so i dont want this
Sets have no order, but i could use order-by to do some sql ordering, but what do i order by? I can't rely on a sequential ID. so i dont want this?
Lists are a duplicate-free collection, where the unique-key is the PK and the index column, so i do want this?
So, using a list, i have the following:
<list cascade="all-delete-orphan" inverse="true" name="Children">
<key>
<column name="Parent_id" />
</key>
<index>
<column name="SortOrder" />
</index>
<one-to-many class="Child" />
</list>
When I insert a parent which a child on it, i see the following SQL:
Insert into Child (id, Parent_id) values (#p0, #p1)
I.e, why doesn't it insert the SortOrder?
If I do a SchemaExport the SortOrder column is created on the Child table.
:(
If I set Inverse="false" on the relationship, i see the same SQL as above, followed by:
UPDATE "Child" SET Parent_id = #p0, SortOrder = #p1 WHERE Id = #p2
Why does it still INSERT the Parent_id with inverse="false" and why doesn't it insert the SortOrder with inverse="true"?
Am I approaching this totally wrong?
Is it also true that assuming this was working, if I were to do:
parentInstance.Children.Remove(parentInstance.Children[0]);
save the parent and reload it, that the list would have a null in position 0, instead of shuffling the rest up?
Thanks
Inverse=true means that NHib will not try to save the actual collection. It will however still cascade the save operation through the collection onto the contained entities, which includes persisting transient instances. This is why you get an insert with no SortOrder - NHib is persisting your transient Child object.
There was a similar question where the solution involved moving to <bag> mappings, but that loses the ordering qualities that <list> has.
Now I've used a <list> before with a <many-to-many> mapping, and there it worked great. There were two SQL insert calls - one to the table containing the child entity and the other to the linking table. I suspect that in your '' case, NHib is still applying the same strategy even though both calls are to the same table.
And finally, if you remove the item at index 0 then you end up with a null value.
So overall, I'd suggest either: 1) move to a <bag> mapping for your collection, and maintaining a specific property for sort order; or 2) move to a <many-to-many> mapping inside your collection.

NHibernate: Change from lazy=true to fetch=join brings back the world

I have a User object/mapping in my application. Each user has a list of contact information (phone, email etc)
the mapping for the user contains:
<bag name="ContactInfo" table="contact_info" lazy="true" cascade="all">
<key column="contact_id"/>
<one-to-many class="...ContactInfo, ..."/>
</bag>
this works fine but i get the n+1 select problem so i need to optimize it a little bit. But for some reason, when I change this to a join and perform some db operation, NH starts updating ALL contact_info objects in the database. When i say db operation i dont mean changinf a contact. i mean anything.
Anyone knows why? thx
EDIT: Just realized that it does it for lazy="true" as well but the second time, after the objects have been loaded. the question of why remains
I'm wondering if your cascades are causing the issue. Do you have cascade=all on your entire graph? If so you may want to re-evaluate your lifecycle strategy.
Here's a though from section 9.9 of NHibernate 1.2 reference (emphasis added)
Mapping an association (many-to-one,
or collection) with cascade="all"
marks the association as a parent/
child style relationship where
save/update/deletion of the parent
results in save/update/deletion of the
child(ren). Futhermore, a mere
reference to a child from a persistent
parent will result in save / update of
the child.
it turns out that an enum field in ContactInfo was the problem. i didnt mind if that particular filed was a string so changing it resolved this issue.

How to map many to many association in NHibernate

I have some database tables named Project, Employee and Branch. An employee can work simultaneously on more than one project. Similarly, in a project, there are multiple employees. Also, a project is conducted at a particular branch. To maintain all these relationships, I am using a project_employee_branch table, which will store the related primary keys of the above three tables. As an example, this project_employee_branch table may contain a row like (1,2,3), which means the project whose primary key is 1, is conducted at branch whose primary key is 3, and one of its project member is an employee whose primary key is 2.
How can I map all these associations in NHibernate? I have mapped many-to-one association using foreign key concept, but I don't know how to map these types of associations, where an intermediate table is involved.
First point I'd make is that your database schema and your description don't match, so please take any advice below in the light of that initial caveat. You say that
a project is conducted at a particular branch
which implies there should be a simple foreign key relationship from project to branch. And of course, if this is what the schema looked like, you would have a two-way many-to-many link table and your life would be much easier.
Anyway, with the three-way combination you have, you need to have a collection of components, where the components have many-to-one properties for the other two object types. There is an example in section 7.2 of the NHibernate documentation, but I think it would look something like this in the mapping for Product:
<set name="BranchEmployees" table="product_employee_branch" lazy="true">
<key column="product_id">
<composite-element class="Purchase">
<many-to-one name="Branch" class="Branch" />
<many-to-one name="Employee" class="Employee"/>
</composite-element>
</set>

NHibernate mapping trouble

I have the following object model:
A top-level abstract class Element with many children and descendants.
A class Event.
Each Element contains a bag of Events.
Each Event has a pointer to the parent Element.
Up till now - pretty standart one-to-many relationship.
But, I want to use table per concrete class strategy. So, the class Element is not mapped to the database. I've tried to solve it this way: each of the concrete descendants of Element defines its own Bag of Events. The problem with this is that each <bag> element contains a <key> element. That key points to the Parent property of Event. It also makes the Parent column in the Events table a foreign key to the table which contains the Bag! But one column can't be a foreign key to several tables and I'm getting an exception on insert.
I've also tried to make the Parent field in the Events table a many-to-any kind of field. That worked. But when I want to make the relation bidirectional, meaning, to add the bags to the descendants of Element I come back to the same problem. Bag => foreign key => exception on insert.
I'm sure this case isn't as unique as it seems.
Thank you in advance for your help.
A little bit late, but I have some advise.
If you are using "table per concrete class", it is as if you would map completely independent tables. So you need separate foreign keys or many-to-any.
many-to-any stores the type name and NH knows to where the foreign key points. But it's impossible to have constraints on such a foreign key.
If you have several bags having items of the same type, make sure they all define different foreign keys:
<class name="A">
<!-- ... -->
<bag name="Events">
<key column="A_FK"/>
<one-to-many class="Event"/>
</bag>
</class>
<class name="B">
<!-- ... -->
<bag name="Events">
<key column="B_FK"/>
<one-to-many class="Event"/>
</bag>
</class>
You can have foreign key constraints on such a foreign key, but no not-null constraint, because only one of these foreign keys is used.
To really have only one foreign key with all the constraints, you need to map the element to a separate table.

How do I make NHibernate delete child references when I delete a parent?

I have a NewsFeed object mapped as such:
<class name="NewsFeed">
<id name="NewsFeedId">
<generator class="guid"/>
</id>
<property name="FeedName" not-null="true" />
<property name="FeedURL" not-null="true" />
<property name="FeedIsPublished" not-null="true" />
</class>
And Users who can have a Set of Selected feeds that they might be intereseted in, mapped like so:
<class name="SystemUser">
<id name="SystemUserId">
<generator class="guid"/>
</id>
<set name="SelectedNewsFeeds" table="SystemUserSelectedNewsFeeds" cascade="all">
<key column="SystemUserId" />
<many-to-many column="NewsFeedId" class="NewsFeeds.NewsFeed, Domain"/>
</set>
</class>
What I want to happen is when I delete the parent NewsFeed then all of the SelectedNewsFeed references get deleted too, without having to load each SystemUser and delete the NewsFeed by hand.
What is the best way to achieve this?
UPDATE: Using cascade="all-delete-orphan" instead of "all" still results in an exception when deleting the NewsFeed:
The DELETE statement conflicted with the REFERENCE constraint "FKC8B9DF81601F04F4". The conflict occurred in database "System", table "dbo.SystemUserSelectedNewsFeeds", column 'NewsFeedId'.
JMCD
Your second approach:
Another alternative is to break the
many-to-many relationship with a join
class in the middle which nHiberate
would be able to determine
parent-child relationships and the
cascade should work.
is actually what the nHibernate folks recommend in their documentation.
Don't use exotic association mappings.
Good usecases for a real many-to-many
associations are rare. Most of the
time you need additional information
stored in the "link table". In this
case, it is much better to use two
one-to-many associations to an
intermediate link class. In fact, we
think that most associations are
one-to-many and many-to-one, you
should be careful when using any other
association style and ask yourself if
it is really neccessary.
Using two one-to-many associations adds the flexibility to easily add other attributes to the "subscription", such as notification preferences for that particular subscription.
Since the relation inside the set is many-to-many, nHibernate is not able to tell which end of the relationship is the child and which is the parent, and the quickest way for me to achieve what I wanted was just to write some SQL that I sent through my repository that deleted the respective news feeds from the collection, and then deleted the parent news feed. The next time the collection was hydrated the changes were reflected.
Another alternative is to break the many-to-many relationship with a join class in the middle which nHiberate would be able to determine parent-child relationships and the cascade should work.
change
cascade="all"
to
cascade="all-delete-orphan"
Reference