NH Prof new feature: Superfluous <many-to-one> update
Yes, I am aware that I said that I would only have two more feature for NH Prof before releasing. But I am currently being held hostage by the new features fairy, and negotiations over a feature freeze seems to have gotten to a stand still. Beside, it is a neat feature.
The actual feature is quite simple. Let us say that we have the following model:
Notice that this is a very common case of bidirectional association, and this is mapped to the following table model:
Notice that while on the object model this is a bidirectional association and is maintained by two different places, it is maintained on a single place in the database.
This is a a very common case, and quite a few people get it wrong. By default, NHibernate has to assume that it must update the column on both sides, so creating a new post and adding it to the Blog’s Posts collection will result in two statements being written to the database:
1: INSERT INTO Posts(Title,
2: Text,
3: PostedAt,
4: BlogId,
5: UserId)
6: VALUES ('vam' /* @p0 */,
7: 'abc' /* @p1 */,
8: '1/17/2009 5:28:52 PM' /* @p2 */,
9: 1 /* @p3 */,
10: 1 /* @p4 */);
11: select SCOPE_IDENTITY ( )
12:
13: UPDATE Posts
14: SET BlogId = 1 /* @p0_0 */
15: WHERE Id = 22 /* @p1_0 */
As you can see, we are actually setting the BlogId to the same value, twice.
Now, there is a very easy fix for this issue, all you have to do is to tell NHibernate on the Blog’s Posts mapping that this is a collection where the responsibility for actually updating the column value is on the other side. This is also something that I tend to check in code reviews quite often. The fix is literally just specifying inverse=’true’ on the <many-to-one> association.
And now NH Prof will detect and warn about such cased:
Beautiful!
This is also the first case in which I am starting to do much more in depth analysis of what is actually going on with NHibernate. I planned to do this sort of thing after the v1.0 release, but as I said, I am held hostage by the new features fairy, and this is my negotiation technique :-)