Showing posts with label NHibernate. Show all posts
Showing posts with label NHibernate. Show all posts

Thursday, May 30, 2013

What's planned for NHibernate 4?

Yesterday Ricardo Peres wrote an article about the state of NHibernate development, comparing it to Entity Framework and noticing that NHibernate's future doesn't look bright. It's pretty much in line with what I meant asking if NHibernate is already dead few months ago. But, as I'm still actively using NHibernate in my project and there are no prospects of changing that, it would be nice if that's not the case.

Although there's no clear roadmap available, it seems that NHibernate's community is planning a major release, bumping the version number to 4. The reason for that is pretty simple - the product is going to switch from .NET 3.5 to 4, mostly to retire Iesi.Collections dependency that provided set implementations that are now partially available in the BCL. This is a major breaking change and that justifies changing the major version number, for sure. Some obsoletes will be cleaned up in the same time.

Are there any new features planned for 4.0? Well, there are some, but I can't say the list is impressive. SQL Server 2012 will be supported better (sequences, limit feature), Ingres9 will be also supported out of the box and few other dialects will have some improvements. But, let's admit it, this is not a big deal for existing users. There are of couse several bugfixes and minor improvements done and planned for that version, i.e. in Linq provider (NH-3186, NH-2852, NH-3056, NH-2915, NH-3256), in mapping-by-code (NH-3280, NH-3313). There is also one possibly significant performance improvement with Linq queries done.

The draft version of release notes is available as a reference for all JIRA issues already resolved. Unfortunately, I can see no "flag ship" feature that might interest, majority of the list is rather maintenance of existing features or cleanup. Definitely not enough to encourage more interest in NHibernate, leaving the framework targeting breaking change the only thing that really justifies releasing this as 4.0 and not as 3.4.

And to make things clear, I'm not complaining that current contributors are lazy. I think Hazzik and Oskar Berggren are doing fantastic job keeping things up and running. The problem is that they are the only really active members of the community. And the size and complexity of the project is big enough to make gaining new contributors really hard, for sure. I've tried to fix one bug once - and I failed.

Anyway, my fingers are crossed in hope of new great features in NHibernate, but, looking objectively, I don't expect anything like that to happen.

Monday, April 15, 2013

NHibernate's LINQ GroupBy capabilities

Recently in the project that is using NHibernate 3.2, I needed to use some aggregations in my database queries. The use case was pretty typical - aggregate some pre-filtered set of invoices by the product sold, count how many sales were there for each product, order the data by total sales value and take top 10 results. It is pretty easy to accomplish in SQL:

SELECT TOP 10 Product, COUNT(*) AS SaleCount, SUM(Value) AS TotalValue
     FROM Invoices
     WHERE Cancelled = 0
     GROUP BY Product
     ORDER BY TotalValue DESC

It is also pretty easy to express in LINQ syntax:

Invoices.Where(i => i.Cancelled == false)
     .GroupBy(i => i.Product)
     .Select(g => new TopSellingProduct 
                  {
                      Product = g.Key, 
                      SaleCount = g.Count(), 
                      TotalValue = g.Sum(i => i.Value) 
                  })
     .OrderByDescending(g => g.TotalValue)
     .Take(10);

I knew that NHibernate's LINQ provider offers limited support for GroupBy operator. Taking into consideration that all the lambda expressions in the query are in fact expression trees that need to be parsed and expressed in SQL, what I expected to be the most problematic, was the Select clause that creates new TopSellingProduct instances (which is not a NHibernate-managed entity) and sets its properties, in case of Sum even using nested lambdas. Actually, this was not a problem at all, even when using anonymous types inside - impressive! NHibernate somehow gets the list of fields and aggregation functions that needs to be fetched and turns it into SELECT clause correctly.

But the query above couldn't be translated into SQL anyway. It turned out that the operators that seemed easier to implement - OrderBy, Take and Skip - were not supported. So with NHibernate 3.2, I could only create an aggregation and fetch all the aggregated values at once, without ordering or paging. In my case, it could mean fetching 50k rows just to show top 10. Not an option.

Fortunately, quick search through the NHibernate's JIRA dashboard gave me the hope that things look better with the newer NHibernate version - 3.3.1. I've upgraded seamlessly using NuGet, and here is the summary of my observations:

SQL featureLINQ syntax exampleNHibernate 3.2NHibernate 3.3.1
SELECT of simple aggregated value; COUNT() function.GroupBy(x => ...).Select(g => g.Count())OKOK
SELECT of anonymous class.GroupBy(x => ...)
.Select(g => new { g.Key, Count = g.Count() })
OKOK
SELECT of named class
.GroupBy(x => ...)
  .Select(g => new MyType 
               {
                 Key = g.Key, 
                 Count = g.Count()
               })
OKOK
SUM(), MIN(), MAX() functions
.GroupBy(x => ...)
  .Select(g => new 
               { 
                 Sum = g.Sum(x => ...), 
                 Min = g.Min(x => ...), 
                 Max = g.Max(x => ...)
               })
OKOK
AVG() function.GroupBy(x => ...).Select(g => g.Avg(x => ...))buggy, truncates value to int (NH-2429)OK
WHERE (condition applied before aggregation).Where(x => ...).GroupBy(x => ...)OKOK
HAVING (condition applied after aggregation).GroupBy(x => ...).Where(g => ...)silent failure, produces subquery instead of HAVING clause and returns wrong results (NH-2883)OK
ORDER BY (sorting).GroupBy(x => ...).OrderBy(g => ...)MismatchTreeNodeException (NH-2781)OK
TOP / LIMIT (number of results).GroupBy(x => ...).Take(10)NotImplementedExceptionOK
OFFSET (paging support).GroupBy(x => ...).Skip(10)NotImplementedExceptionOK

Things look MUCH better now - everything what I need (and a bit more) is correctly supported with the newest LINQ provider.

Monday, April 8, 2013

NHibernate Equals implementation with proxies vs. ReSharper - or yet another couple of hours lost

I'm already quite sensitive to missing Equals and GetHashCode implementations for NHibernate entities or value types that caused issues like re-inserting or duplicating items within collections hundred times.

A good rule for Equals and GetHashCode (that is clearly stated in the documentation) is to make it do comparisons based on the set of fields that create "business" (real-life) identification of an object whenever possible - and not on database-level identifiers. It works well also when comparing objects from different sessions (detached) or not yet persisted (transient) - without any "unproxying" magic.

Today, my personal counter of hours devoted into cursing and fighting NHibernate-related corner cases or strange issues increased once again. I have an interesting (two hours later - frustrating) case of entities being mixed up in spite of correct SQL queries issued. And I was quite confident that my ReSharper-generated Equals and GetHashCode methods were correct and the root cause was somewhere else. Just look how simple was the code of my entity:

public class City
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }

    public virtual bool Equals(City other)
    {
        if (ReferenceEquals(null , other))
            return false ;
        if (ReferenceEquals(this , other))
            return true ;
        return Equals(other.Name, Name);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null , obj))
            return false ;
        if (ReferenceEquals(this , obj))
            return true ;
        if (obj.GetType() != typeof (City))
            return false ;
        return Equals((City ) obj);
    }

    public override int GetHashCode()
    {
        return (Name != null ? Name.GetHashCode() : 0);
    }
}

I am comparing City instances using a natural key - its name. In the faulty code I was querying the database for different entities that reference City and later the referenced cities were compared for equality. Here is the simplified sketch of the test case (written in Machine.Specifications) with initialization that creates the object graph and two fetching scenarios as a separate tests.

public class EqualsTest : DatabaseTests
{
    Establish context = () => sut.WithinSessionAndTransaction(sess =>
    {
        var city = new City() { Name = "Llanfairpwllgwyngyll" };
        sess.Persist(city);
        sess.Persist( new Address () { City = city });
        sess.Persist( new District () { City = city });
    });

    It should_have_equal_cities = () => sut.WithinSessionAndTransaction(sess =>
    {
        var address = sess.Query<Address>().Single();
        var district = sess.Query<District >().Single();

        district.City.ShouldEqual(address.City);
    });

    It should_correctly_use_city_in_lookup = () => sut.WithinSessionAndTransaction(sess =>
    {
        var address = sess.Query<Address >().Single();
        var districts = sess.Query<District >().ToLookup(x => x.City);

        districts[address.City].ShouldNotBeEmpty();
    });
}

In the first test I'm doing the direct comparison of cities, in the second one I'm creating a lookup table with City instance as a key. In both cases lazy loading takes place so I'm working with NHibernate-generated City proxies. But it should not be a problem, as NHibernate guarantees object identity within a single session, right?

Well, uhm, the first test passes as expected, but the second test fails! It turned out that the City instance used as the key in districts (proxy instance) does not maintain identity with the proxy instance fetched for Address instance, even if they are both pointing at the same (single) city and are used within single session!

I'm not sure why this happens and I'm pretty confident it shouldn't, but fortunately the workaround is quite easy. As the proxies instances used in Address and District instances are now different references, they are compared using the Equals method we've provided. When Equals (or, more precisely, GetHashCode) is called on one of the objects to compare it with the second one, lazy fetch from the database is performed and it becomes the "real", unproxied object. But the second one doesn't - it is still CityProxy instance. And Equals offered by ReSharper, when checking objects types, unfortunately expects the type to exactly match:

        if (obj.GetType() != typeof (City))
            return false ;

But obj.GetType() is a CityProxy and we're exiting the comparison with the negative result here. The workaround is just to replace that exact check with more semantic one, checking only whether obj can be treated as a City instance:

        if (!(obj is City))
            return false ;

In this case, nor City neither CityProxy are eliminated, NHibernate can continue to compare city names and see that the proxy points to the same objects. This simple change done - and voilĂ  - we have two tests passed!

Thursday, February 14, 2013

NHibernate's test suite is a mess

I'm not doing it on purpose, I haven't converted into fighting NHibernate's foe, but it looks it will be another rather not encouraging post about NHibernate. But when I saw it's so called unit tests suite, I couldn't resist on sharing my thoughts.

NHibernate is using CodeBetter's TeamCity. We can see more than 200 tests ignored there. This doesn't bode well itself.

I've looked at NHibernate 3.2 source code I already had on the disk, but I've also compared it a bit with the current GitHub version and the situation haven't changed drastically since then.

Looking at the scope of most of the tests, they are more integration than unit tests - they run a complete top-down calls. This means that it requires a deep knowledge of the system to tell what went wrong when test fails and virtually no chance for anyone not being deep inside the codebase to know how to fix it.

It's nothing wrong with integration testing, of course, but not if the recurring pattern is that they are just a smoke tests - verifying only if there was an exception thrown or not. I've run the tool to find tests without assertions (that I'm going to publish some day) - and it turned out that there are 328 assertionless tests! More than 7% of the whole suite doesn't actually verify any outcome. And it is for sure possible to remove a whole lot of the code, even theoretically test-covered code, and cause no test to fail!

But way more interesting are the tests that do not increase the code coverage even incidentally! I like this one:

[TestFixture]
public class Fixture : BugTestCase
{
    [Test]
    public void Bug()
    {
        // Do nothing, we only want to check the configuration
    }
}

Note also the incredibly pure naming schema. There are 36 tests named Bug and 35 named just Test in the codebase and at least 80 test classes named Fixture. There is some kind of convention for namespaces, though, but with a lot of exceptions.

What else can we see in the NHibernate's "unit" test suite? Well, everything! We have a real file system access, real database access, time measurement, dependency on driver configuration etc. There is a lot of code which should be unit-tested itself.

Those tests, no matter if we name it unit-, integration- or whatever-tests, are poorly factored and contain multiple asserts. Look at the MasterDetail test here - 180 lines of code and 40 asserts in single test! The longest class test I've encountered was FooBarTest - it has 5729 lines (and has pretty nice name, hasn't it?).

And for the end, this is the line I liked the most:

catch(Exception e)
{
    Assert.IsNotNull(e); //getting ride of 'e' is never used compile warning
}

Wow, we have an assertion! But, as the comment suggests, it was added only to shut the compiler up, not to verify anything valuable. Not to mention that there are better ways to cope with compiler warnings...

Anyway, if you'd ever be looking for a good unit test suite to learn something from, at least you know where definitively not to look!

Saturday, September 15, 2012

NHibernate LINQ Pitfalls: Too many joins with deep conditions

Although I've just discussed whether NHibernate became obsolete, it doesn't mean that I'm no longer maintaining or developing applications that use it. It'll take at least few years to completely phase it out and in the meantime we still have some problems with it and we still need to know how to use it.

One of recent surprises we had with NHibernate was when querying the database using LINQ provider and condition in our query was checking a reference value not directly in queried object, but in another object it references (yes, I know it is breaking the Law of Demeter), like this:

var firstQuery = sess.Query<RootNode>()
    .Where(x => x.Child.GrandChild.Id == 42)
    .FirstOrDefault();

The condition on GrandChild uses its key value only, so looking at the database tables, joining the GrandChildNode is not needed - all the information used by this query sits in RootNode. Surprisingly, NHibernate 3.2 not only joins GrandChildNode, but also joins RootNode for the second time, only to completely ignore it. That makes 4 tables total.

However, when we change the way we're looking for a grand child and use proxy object created by ISession's Load method, we get expected and optimal query with only 2 tables joined.

var secondQuery = sess.Query<RootNode>()
    .Where(x => x.Child.GrandChild == sess.Load(42))
    .FirstOrDefault();

This bug was already found and is fixed in version 3.3 (and surprisingly, was not present in 3.1) - so it affects only NHibernate 3.2. But I think it's worth mentioning as it may have potentially large performance impact if you're using that version.

Friday, September 7, 2012

Is NHibernate dead?

Before discussing the question from the title, let me answer another one: Is this blog dead? Definitely no. Summer time distracted me a bit, but I'm hoping to get back to writing now :)

So it's more than half a year since I've concluded my series about NHibernate's mapping-by-code. The series is still surprisingly popular, there are quite a lot of hits from Google every day. I've also just reached 50 upvotes at Stack Overflow in a question about where to find some docs and examples for mapping-by-code. Thanks for this!

Quick googling for "mapping by code" and skimming through NHForge website convinced me that still there is nothing better available in the topic. Moreover, none of the bugs I've encountered half a year ago made any progress - all issues left unresolved and unassigned back then are in the same state right now. These facts are a bit sad, as I saw the mapping-by-code feature as quite revolutionary and shaping the future of NHibernate.

Well, and here comes the question - maybe there is no future? Maybe everything what is needed in the subject of object-relational mapping is already there and no development is needed? Ohloh stats notice some development in NHibernate project, but the pace is rather slowing down. No new releases are planned according to the roadmap on issue tracker. There are 25 issues classified as "Critical" unresolved, oldest waiting for more than 20 months by now. The development in a third-party ecosystem has already stopped - see the Ohloh graphs for NHibernate.Contrib or Fluent NHibernate, to name the most significant ones.

In my opinion, the reason for NHibernate's agony is simple. It was already discovered many times that applications nowadays are mostly web-based, read-intensive, not so data-centric and not consisting complicated data manipulation as few years ago. With the advent of mature NoSQL engines - free, easy to use and full of neat features - like RavenDB and - on the other side - with lightweight ORM-like tools like Dapper or Simple.Data, that cover at least 95% of ORM features needed to effectively handle newly-designed relational databases, we just don't need to use such a big and heavy tool like NHibernate.

Legacy databases are still a niche for NHibernate, for sure, but how many legacy databases that are not OR-mapped yet we still have out there? And for fresh developments, I'd say that unless you're designing some kind of specific data-driven application, it is more effective (both in terms of development effort and performance) to stick with either NoSQL or some lightweight ORM instead of NHibernate.

NHibernate is a great tool, but time goes by pretty quickly. The context of our work changes from year to year and even good tools some day must be superseded by better ones, that are more suitable for nowadays needs. And I think that day for heavy, multi-purpose ORM's like NHibernate has just come.

Tuesday, May 8, 2012

Migrating from identity to HiLo

Generally, NHibernate is not the best solution when our application is concerned mainly around batch data loads. But there are a lot of scenarios, like initialization, when medium-sized batch inserts make sense in every application.

If our database table primary key is generated with identity generator and we try to persist objects one by one in a loop, our performance can hurt and NHProf starts to complain that we're doing too many database calls. In fact, for every row inserted, NHibernate needs to do a separate round-trip to the database, because it needs to fetch the identity value generated every time.

The solution is to switch our primary key generation strategy from identity to HiLo. HiLo is composing the identifier from two parts, only one of which comes from the database. This means that when NHibernate knows that part (called high), it can insert a number of rows in a single round-trip.

Assuming the size of the batch is sufficient (less than number of rows to be inserted - let's call it N), the number of round-trips needed to persist the data with NHibernate decreased to 2 (from N with identity).

The problem arises when we already have the database in production and we can't just change the generation strategy in the mapping. First, we need to remove the identity attribute from our Id column, what is not so trivial with SQL Server. Actually it's easier to create new column for the new primary key, rewrite the values and drop the previous one. The second issue with non-empty tables is that NHibernate's HiLo needs to start counting from the current highest identity value + 1, otherwise we'll end up with primary key violation.

Here is the SQL Server script I wrote to cope with these issues. It creates new primary key without identity attribute, drops the previous one after migrating the values, creates HiLo infrastructure for NHibernate and populates it with current production values. Feel free to use it!

sp_rename 'TheTable.Id' , 'Id_Identity'
go

alter table TheTable
    add Id bigint
alter table TheTable
    drop constraint Id_PK
go
    
update TheTable
    set Id = Id_Identity
go

alter table TheTable
    alter column Id bigint not null
go

alter table TheTable
    drop column Id_Identity
alter table TheTable
    add constraint Id_PK primary key(Id)
go

create table HiLo (
    NextHi int primary key
)

insert into HiLo (NextHi) values ((select (max(Id) / 32) + 1 from TheTable))

Note that I needed to specify the size of the batch (max_low) in the last line, in order to calculate the starting NextHi correctly.

Sunday, April 15, 2012

NHibernate's inverse - what does it really mean?

NHibernate's concept of 'inverse' in relationships is probably the most often discussed and misunderstood mapping feature. When I was learning NHibernate, it took me some time to move from "I know where should I put 'inverse' and what then happens" to "I know why do I need 'inverse' here and there at all". Also now, whenever I'm trying to explain inverses to somebody, I find it pretty hard.

There are a lot of explainations over the net, but I'd like to have my own one. I don't think that the others are wrong, it'll just help me arrange my own understanding and if anyone else take advantage of this, that's great.

Where do we use inverse?

First, some widely-known facts, next we'll elaborate on few of them.

  • Inverse is a boolean attribute that can be put on the collection mappings, regardless of collection's role (i.e. within one-to-many, many-to-many etc.), and on join mapping.
  • We can't put inverse on other relation types, like many-to-one or one-to-one.
  • By default, inverse is set to false.
  • Inverse makes little sense for unidirectional relationships, it is to be used only for bidirectional ones.
  • General recommendation is to use inverse="true" on exactly one side of each bidirectional relationship.
  • When we don't set inverse, NHProf will complain about superfluous updates.

What does it mean for a collection to be 'inverse'?

The main problem in understanding 'inverse' is it's negating nature. We're not used to setting something up in order to NOT take an action. Inverse set to true means "I do NOT maintain this relationship". Hence, inverse set to false means "I DO maintain this relationship".

It'll be much more understandable if we could go to the opposite side of the relationship and be positive there: "This side maintains the relationship" and NHibernate would automatically know that the other side doesn't (*). But it is implemented as it is - we have to live with inverse's negative character.

Each relationship is represented in the database as an identifier of a related table row in the foreign key column at 'many' side. Why at 'many' side? Because that's how we do relationships in the relational databases. The column "holding" the association is always at 'many' side. It's not possible to keep the association at 'one' side because we'd have to insert many values into one database field somehow.

So what does it mean for a collection in NHibernate to maintain the relationship (inverse="false")? It means to ensure that the relation is correctly represented in the database. If the Comments collection in the Post object is responsible for maintaining the relationship, it has to make sure all its elements (comments) have foreign keys set to post's id. In order to do that, it issues a SQL UPDATE statement for each Comment, updating its Post reference. It works, the relationship is persisted correctly, but these updates often do not change anything and can be skipped (for performance reasons).

Inverse="true" on a collection means that it should not take care whether the foreign keys in the database are properly set. It just assumes that some other party will take care of it. What do we gain? We have no superfluous UPDATE statements. What can we lose? We have to be sure that the second side actually takes over the responsibility of maintaining the association. If it doesn't, nobody will and we'll be surprised that our relationship is not persisted at all (NHibernate will not throw an error or so, it won't guess that it's not what we've expected).

When should we set inverse="true"?

Let's consider one-to-many first. Our relationship must be bidirectional and have entities (not value types) at both sides for inverse to make sense. Other side ('many' side) is always active, we can't set inverse on many-to-one. This means that we should put inverse="true" on the collection, provided that:

  • our collection is not explicitly ordered (like <list>) - it is i.e. <bag> or <set>; ordered lists have to be active in order to maintain the ordering correctly; 'many' side doesn't know anything about the ordering of collection at 'one' side
  • we actually set the relationship at 'many' side correctly

Consider the example:

public class Post
{
public virtual int Id { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}

public class Comment
{
public virtual int Id { get; set; }
public virtual Post Post { get; set; }
public virtual string Text { get; set; }
}

// ...

var comment = new Comment() { Text = "the comment" };
session.Persist(comment);
post.Comments.Add(comment);

We are not setting Post property in Comment class as we may expect NHibernate will handle that as we append our comment to the collection of comments in particular Post object (**). If the post.Comments collection is not inverse, it will actually happen, but quite ineffectively:

We've inserted null reference first (exactly as it was in our code) and then, as the collection is responsible for maintaining the relationship (inverse="false"), the relationship was corrected by separate UPDATE statement. Moreover, in case we have not null constraint on Comment.Post_id (which is actually good), we'll end up with exception that we can't insert null foreign key value.

Let's see what happens with inverse="true":

There's no error, but the comment is actually not connected to the post, despite we've added it to a proper collection. But using inverse, we've explicitly turned off maintaining the relationship by that collection. And as we don't set the relationship on Comment side, noone does.

The solution of course is to explicitly set comment's Post property. It is good from object model perspective, too, as it reduces the amount of magic in our code - what we've set is set, what we haven't set is not set magically.

var comment = new Comment() { Text = "the comment", Post = post };
session.Persist(comment);
post.Comments.Add(comment);

Much better now:

Time for many-to-many. Again, inverse makes sense only when we've mapped both sides. We have to choose one side which is active and mark the second one as inverse="true". Without that, when both collections are active, both try to insert a tuple to an intermediate table many-to-many needs. Having duplicated tuples makes no sense in most cases. For some suggestions how to choose which side is better in being active, see my post from December.

To sum up

Left sideRight sideInverse?
one-to-manynot mappedmakes no sense - left side must be active
one-to-manymany-to-oneright side should be active (left with inverse="true"), to save on UPDATEs
(unless left side is explicitly ordered)
many-to-manynot mappedmakes no sense - left side must be active
many-to-manymany-to-manyone side should be active (inverse="false"), the other should not (inverse="true")

______

(*) There are of course reasons why NHibernate doesn't do assumptions about other sides of relationships like that. The first one is to maintain independence between mappings - it will be cumbersome if change in mapping A modifies the B behaviour. The second one are ordered collections, like List. The ordering can be automatically kept by NHibernate only when collection side is active (inverse="false"). If the notion of being active is managed on the other side only, changing the collection type from non-ordered to ordered would require changes in both mappings.

(**) Note that inverse is completely independent from cascading. We can have cascade save on collection and it does not affect which side is responsible for managing the relationship. Cascade save means only that when persisting Post object, we're also persisting all Comments that were added to the collection. They are inserted with null Post value and UPDATEd later or inserted with proper value in single INSERT, depending on object state and inverse setting, as described above.

Tuesday, April 3, 2012

Table per subclass using a discriminator with mapping-by-code

Recently xanatos in a comment to one of my mapping-by-code series post asked how to implement hybrid-mode inheritance with both table per subclass and discriminator columns using mapping-by-code. I think this scenario is quite exotic (why do we need a discriminator column if we have separate tables?), but the documentation explicitly mentions this possibility, so it should be possible with mapping-by-code, too.

Here is the expected XML mapping fragment:

<class name="Payment" table="PAYMENT">
<id name="Id" type="Int64" column="PAYMENT_ID">
<generator class="native"/>
</id>
<discriminator column="PAYMENT_TYPE" type="string"/>
<property name="Amount" column="AMOUNT"/>
...
<subclass name="CreditCardPayment" discriminator-value="CREDIT">
<join table="CREDIT_PAYMENT">
<key column="PAYMENT_ID"/>
<property name="CreditCardType" column="CCTYPE"/>
...
</join>
</subclass>
</class>

And here is how to do it in mapping-by-code:

public class PaymentMap : ClassMapping<Payment>
{
public PaymentMap()
{
Id(x => x.Id, m => m.Generator(Generators.Native));
Discriminator(d => d.Column("PaymentType"));
Property(x => x.Amount);
}
}

public class CreditCardPaymentMap : SubclassMapping<CreditCardPayment>
{
public CreditCardPaymentMap()
{
DiscriminatorValue("CREDIT");
Join("CreditPayment", j => j.Property(x => x.CreditCardType));
}
}

I'm impressed again how easily XML mapping can be translated to mapping-by-code syntax.

Sunday, March 11, 2012

Mapping-by-code and custom ID generator class

In the comments to one of my mapping-by-code posts Cod asked if it is possible to specify a custom ID generator class within mapping-by-code mappings. I didn't know the answer but the topic seems to be interesting enough to figure it out.

The answer is of course positive - mapping-by-code API is flexible enough to support that. Let's remind how we normally specify the generator class to be used:

Id(x => x.Id, m =>
{
m.Generator(Generators.Native, g => g.Params(new
{
// generator-specific options
}));
});

The Generator method's first parameter expects an instance of IGeneratorDef class. NHibernate provides a set of predefined ones in Generators static class - see the full list here - but we may provide our own implementation as well.

Let's hook up a custom generator class as implemented in this NHForge's article. FDPSequence class defined there is an integer-based, parametrized generator (implementation of NHibernate's IIdentifierGenerator). To use it within mapping-by-code, we need to prepare IGeneratorDef class accordingly. But that's pretty easy:

public class FDPSequenceDef : IGeneratorDef
{
public string Class
{
get { return typeof(FDPSequence).AssemblyQualifiedName; }
}

public object Params
{
get { return null; }
}

public Type DefaultReturnType
{
get { return typeof(int); }
}

public bool SupportedAsCollectionElementId
{
get { return true; }
}
}

We have to implement 4 properties:

  • Class is an equivalent of class attribute in XML - this is the place where we need to specify our custom generator assembly qualified name.
  • Params allows us to create non-standard <param> elements equivalents. We could return an anonymous object with values set i.e through the constructor - but I don't think it is needed as we can always pass parameters through the second Generator method's parameter, as an anonymous object, too.
  • DefaultReturnType specifies what is the type generated by our custom generator (may be null, NHibernate will figure it out through the reflection later)
  • and SupportedAsCollectionElementId obviously specifies if our generator is usable within collection elements.

Having FDPSequenceDef in place, we just need to pass it to Generator method in mapping-by-code:

Id(x => x.Id, m => m.Generator(new FDPSequenceDef()));

And we're done! The XML generated looks like expected and the generator is working for us:

<id name="Id" type="Int32">
<generator class="NHWorkshop.FDPSequence, NHWorkshop, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</id>

Friday, February 17, 2012

Mapping-by-Code & Fluent NHibernate issues summary

In my mapping-by-code posts series I've just completed, I reviewed the capabilities of both mapping-by-code and Fluent NHibernate in comparison to plain old XML mappings. There are some more or less serious bugs on both sides, as well as both solutions don't offer everything XML does. In each case, when I found the issue worth mentioning, I was looking if it was already reported and reported it myself if not. Here is the quick summary:

Mapping-by-Code

Fluent NHibernate


As you can see, the number of issues I've encountered is very similiar for both mapping-by-code and Fluent NHibernate. For mapping-by-code, majority of them were already reported and actions were taken. Actually, 5 of them are already resolved and wait for NH 3.3 release. I've reported 3 new issues (one of which was fixed in few days) and extended another one.

For Fluent NHibernate, I've reported 8 issues out of 10 encountered. Sadly, by now, none of them were even commented. It looks like there's no active development on FNH. I tend to agree that leaving issues in no man's land with no status at all is a sign of a neglected community. I'd prefer to have these issues closed with "won't do" status than ignored, for sure.

Wednesday, February 15, 2012

NHibernate's mapping-by-code - the summary

Six weeks ago, when I started my experiments with NHibernate's 3.2 new mapping feature - mapping-by-code, I was a loyal Fluent NHibernate user and a fan of method chains in APIs. My first impression about mapping-by-code was that it seems to be a good direction, but it's still immature and - what's important - not documented at all. I decided to have a deeper look and it turned into almost twenty parts series exploring all the possible mappings - probably the only complete guide to mapping-by-code on the web so far. Time to sum the series up.

Let's start with what mapping-by-code is. It is an XML-less mapping solution being an integral part of NHibernate since 3.2, based on ConfORM library. Its API tries to conform to XML naming and structure. There's a strong convention in how the mapping methods are built. Its names are almost always equal to XML elements names. The first parameter points to the mapped property, second is for its options corresponding XML attributes (and XML <key> element, if applicable) and the rest of parameters, if any, corresponds to nested XML elements. It's very convenient for those familiar with XML schema or for documentation readers.

Mapping-by-code also came with very powerful mapping by convention tool - ConventionModelMapper. It is highly flexible and customizable, but customizing it may not even be needed, as by default it is able to figure out mappings even for components or maps. The only thing it can't map automatically are bidirectional relationships - but it was pretty easy to fix this using conventions (I've updated my conventions since first published - it now supports all kinds of collections, inheritance and more - feel free to use it).

Here is the full table of contents of my mapping-by-code series.

  1. First impressions
  2. Naming convention resembling Fluent
  3. Property
  4. Component
  5. ManyToOne
  6. inheritance
  7. dynamic component
  8. Set and Bag
  9. OneToMany and other collection-based relation types
  10. concurrency
  11. OneToOne
  12. Join
  13. Any
  14. List, Array, IdBag
  15. Map
  16. Id, NaturalId
  17. composite identifiers
  18. entity-level mappings

And what about Fluent NHibernate? Hiding the XML was a great idea, but simplifying the mappings went too far, in my opinion. I've already mentioned the mess caused by concept name changes made in Fluent NHibernate (1) (2) - I wouldn't repeat it again. Moreover, XML mapping is a tree structure and it just doesn't fit into single method chains. Fluent NHibernate's API bypasses this limitations by prefixing method names (like KeyColumn) or by falling back to the interface that uses Action<T> (i.e. in Join or Component mapping), quite similiar to mapping-by-code API. Method chaining also makes it hard to reuse the same concepts in different contexts. It's lot easier in mapping-by-code way - i.e. Column mapping is the same in every mapped feature and it is handled by exactly the same code.

Don't get me wrong. I think FNH was a good and useful project. But I've used it as the only existing alternative to cumbersome and verbose XML mapping. And now, when we have an alternative that is integrated into NHibernate (no external dependency and versioning issues), more efficient (no XML serialization) and with better API (no ambiguity, NH naming kept), the purpose of FNH's existence is highly reduced.

Monday, February 13, 2012

Mapping-by-Code - entity-level mappings

We're finally reaching the end of mapping-by-code series. In the last post about mapping possibilities I will cover all options mapped directly at the entity level, that do not map to a column in the database. They define different entity behaviors and customization options and majority of them translates to elements or attributes in XML <class> mapping. Let's go through these possibilities.

Table("tableName");
Schema("schemaName");
Catalog("catalogName");

These are pretty obvious ones - they define where in the database the entity is represented.

EntityName("entityName");
DynamicInsert(true);
DynamicUpdate(true);
BatchSize(10);
Lazy(true);
SelectBeforeUpdate(true);
Mutable(true);
Synchronize("table1", "table2");
SchemaAction(NHibernate.Mapping.ByCode.SchemaAction.All); // or .Drop, .Export, .None, .Update, .Validate
  • EntityName allows to define an alias for the entity - useful when we're mapping the same class more than once.
  • DynamicInsert and DynamicUpdate decide whether to restrict constructed SQL queries only to properties modified explicitly (by default - with these options turned off - NHibernate inserts/updates all properties everytime).
  • BatchSize is an last resort solution for Select N+1 problem - it sets up batching when loading entities in a loop.
  • Lazy(false) completely turns off lazy loading for the entity (no proxy is created).
  • SelectBeforeUpdate is to fetch the data before update, surprisingly - another way of dealing with concurrency.
  • Mutable(false) reduces the NHibernate's infrastructure when the entity is read-only for our application (i.e. when mapped to a database view or to a lookup-only table).
  • Synchronize informs NHibernate that the entity is derived from another and it should care not to return stale data when querying the derived entity.
  • SchemaAction is for hbm2ddl tool to decide what should it do when creating session factory.
Cache(c =>
{
c.Usage(CacheUsage.NonstrictReadWrite); // or .ReadOnly, .ReadWrite, .Transactional
c.Include(CacheInclude.All); // or .NonLazy
c.Region("regionName");
});

Cache is for second-level caching. We need to turn it on explicitly for every entity we want to cache by defining Usage model at least.

Filter("filterName", f => f.Condition("filter SQL condition"));
Where("SQL condition");

Filter and Where are two different ways of narrowing the scope of entities loaded and managed by NHibernate.

SqlInsert("custom SQL");
SqlUpdate("custom SQL");
SqlDelete("custom SQL");
Subselect("custom SQL");

These four are for customizing CRUD operations on the entity. Useful i.e. when access to the table should be done through the stored procedures only.

Loader("loaderReference");
Persister<CustomPersister>();
Proxy(typeof(ProxyType));

And these three are even more low-level possibilities for customization. Haven't explored it thoroughly, but I don't think there are lot of scenarios when they are needed.

There are some XML attributes that do not have an equivalent in mapping-by-code yet. These are tuplizer, resultset, abstract, polymorphism, optimistic-lock, check, rowid, node and import. Apart from optimistic-lock, they don't look important.

Fluent NHibernate's equivalents

FNH offers a bit different subset of entity-level options. Some of mapping-by-code deficiencies are covered (like OptimisticLock, Polymorphism, ImportType, CheckConstraint, Tuplizer), some features are missing instead (like Catalog, Synchronize, Loader). Here are the options available:

Table("tableName");
Schema("schemaName");

EntityName("entityName");
DynamicInsert();
DynamicUpdate();
BatchSize(10);
LazyLoad();
OptimisticLock.All(); // or .Dirty, .None, .Version
SelectBeforeUpdate();
ReadOnly();
Polymorphism.Explicit(); // or .Implicit
SchemaAction.All(); // or .Drop, .Export, .Update, .Validate, .Custom

Cache.IncludeAll() // or .IncludeNonLazy
.Region("regionName")
.NonStrictReadWrite(); // or .ReadOnly, .ReadWrite, .Transactional, .CustomUsage<>

ApplyFilter("filterName", "SQL condition");
Where("SQL condition");

CheckConstraint("check");
ImportType<Import>().As("alternativeName");

SqlInsert("sql query").Check.None(); // or .RowCount
SqlUpdate("sql query");
SqlDelete("sql query");
SqlDeleteAll("sql query");
Subselect("sql query");
StoredProcedure("command", "sql query").Check.None();

Persister<CustomPersister>();
Proxy(typeof(ProxyType));
Tuplizer(TuplizerMode.Xml, typeof(Tuplizer));

There are some name changes when compared to XML attributes or elements names. LazyLoad is for lazy, CheckConstraint for check, ReadOnly for mutable="false" and ApplyFilter covers filter element. StoredProcedure is used internally within SqlXYZ elements - I don't know why this method is in public API. There is also one elements that should not be there - SqlDeleteAll do not have an equivalent in XML mapping and can't be used.


And that's all for mappings exploration! I'll probably summarize the series in a separate post or two.

Friday, February 10, 2012

Mapping-by-Code - composite identifiers

Recently we've talked about surrogate primary keys. Let's move on to different foreign key types supported by NHibernate. We have composite keys available in two different ways, depending on whether we have the key represented in object model as a component (ComponentAsId) or just as several properties in the entity (ComposedId).

ComponentAsId(x => x.Key, m =>
{
m.Property(x => x.KeyPart);
// etc.
});

ComposedId(m =>
{
m.Property(x => x.KeyPart);
// other key parts
});

ComponentAsId is an equivalent of <composite-id> XML element with name and class attributes. ComposedId is an equivalent of <composite-id> without attributes. Both in ComponentAsId and ComposedId we need to specify properties taking part in the key and we do it in a standard way, known i.e. from Component mapping. In both cases a way to specify unsaved-value and mapped attributes is missing.

ComponentAsId is unfortunately broken in NHibernate 3.2 - it ignores the property name pointing to key component. It will be fixed in 3.3, in the meantime we have to use XML mapping here or modify the HbmMapping class directly, like this:

mapping.RootClasses.Single(x => x.Name == typeof(EntityWithComponentAsId).Name).CompositeId.name = "Key";

Fluent NHibernate's equivalents

Composite identifiers are supported well, too, in both variants.

// ComposedId equivalent
CompositeId()
.KeyProperty(x => x.KeyPart)
.KeyReference(x => x.KeyReference)
.UnsavedValue("string?")
.Access.Field();

// ComponentAsId equivalent
CompositeId(x => x.Key)
.KeyProperty(k => k.KeyPart)
.KeyReference(k => k.KeyReference)
.Not.Mapped()
.UnsavedValue("string?")
.Access.Field();

We have KeyProperty as an equivalent of key-property element in XML (mapped with Property in mapping-by-code). We have KeyReference for key-many-to-one (mapped with ManyToOne in mapping-by-code). We have Mapped method as an direct equivalent of mapped attribute from XML as well as UnsavedValue method for unsaved-value attribute (but why it is string-typed?).

There's also one more method in chain - ComponentCompositeIdentifier. It seems to be an alternative syntax for ComponentAsId case, but I couldn't make it produce valid XML mapping and the functionality is already covered, so I'll ignore it.

Wednesday, February 8, 2012

Mapping-by-Code - Id, NaturalId

I've already finished going through all the Ayende's posts about NHibernate mappings and analysing its mapping-by-code equivalents, but I feel I haven't covered everything. The first quite obvious NHibernate's feature Ayende skipped is primary key mapping. There are several options available - from identity columns, native generators, through HiLo and sequences, up to composite identifiers. As always, I'm not going to explain how each of them works, I'll keep focus on mapping-by-code and Fluent NHibernate's possibilities.

The most common primary key mapping is available through Id method.

Id(x => x.Id, m =>
{
m.Column("id");

m.Generator(Generators.Native, g => g.Params(new
{
// generator-specific options
}));

m.Length(10);
m.Type(new Int32Type());
m.Access(Accessor.Field);
});

There are several features missing - like unsaved-value (will be added in NHibernate 3.3) or DDL column options.

Probably the most important option is Generator. It specifies the way NHibernate (or database) generates unique values. There are 8 predefined types of generators available through static Generators class:

public static class Generators
{
// assigning the values is client code responsibility
public static IGeneratorDef Assigned { get; }

// whatever is native in underlying database
public static IGeneratorDef Native { get; }

// High-Low
public static IGeneratorDef HighLow { get; }

// Guid
public static IGeneratorDef Guid { get; }

// sequential Guid
public static IGeneratorDef GuidComb { get; }

// database-level sequence
public static IGeneratorDef Sequence { get; }

// database-level identity
public static IGeneratorDef Identity { get; }

// driven by referenced entity
public static IGeneratorDef Foreign<TEntity>(Expression<Func<TEntity, object>> property);
public static IGeneratorDef Foreign(MemberInfo property);
}

Some of those can have additional parameters specified using Generator method second parameter and anonymous type inside Params call. This is probably the only place in mapping-by-code when we have not strongly-typed options, but it's not worse than in XML.

Here are the parameters available for HighLow, as well as its default values:

m.Generator(Generators.HighLow, g => g.Params(new
{
max_lo = Int16.MaxValue, // size of ids range reserved at once - Int16.MaxValue by default
table = "hibernate_unique_key",
schema = null,
catalog = null,
column = "next_hi",
where = "", // additional SQL condition applied to query when fetching next_hi value
}));

And here is the similiar list for Sequence:

m.Generator(Generators.Sequence, g => g.Params(new
{
sequence = "hibernate_sequence",
schema = null,
catalog = null,
parameters = null, // driver-specific DDL string to be appended to create command
}));

There's another id-related option available - natural ID. It is in fact not a primary key handling option, but it's related, so I decided to include it here. It is available through NaturalId mapping method.

NaturalId(m =>
{
m.Property(x => x.KeyPropery);
// etc...
});

Mutable attribute from XML natural-id element has no equivalent in mapping-by-code.

Fluent NHibernate's equivalents

For mapping surrogate keys there is Id method chain available. Let's see first which of the generators are available directly:

Id(x => x.Id)
.GeneratedBy.Assigned()
.GeneratedBy.Custom<CustomGenerator>()
.GeneratedBy.Foreign("propertyName")
.GeneratedBy.Guid()
.GeneratedBy.GuidComb()
.GeneratedBy.GuidNative()
.GeneratedBy.HiLo("table", "column", "maxLo", "where")
.GeneratedBy.Identity()
.GeneratedBy.Increment()
.GeneratedBy.Native("sequenceName")
.GeneratedBy.Select()
.GeneratedBy.SeqHiLo("sequenceName", "maxLo")
.GeneratedBy.Sequence("sequenceName")
.GeneratedBy.SequenceIdentity("sequenceName")
.GeneratedBy.TriggerIdentity()
.GeneratedBy.UuidHex("format")
.GeneratedBy.UuidString();

All the parameters are optional. Apart from that, there is an additional configuration interface available in most generators:

p => p.AddParam("name", "value")

As we can see, the number of options available directly is higher than in mapping-by-code.

Time to look at different id mapping options.

Id(x => x.Id)
.Column("id")
.Length(10)
.CustomType<CustomType>()
.Access.Field()
.UnsavedValue(0)
.Check("sql constraint")
.CustomSqlType("sqlType")
.Default(0)
.Index("idx")
.Nullable()
.Precision(10)
.Scale(10)
.Unique()
.UniqueKey("uniq");

There are a lot more options available in FNH than in mapping-by-code. I think that at least some of them are completely useless (like defining unique key name), but this is not a FNH's bug, this is what NHibernate mapping does allow, surprisingly.

NaturalId is supported well, too.

NaturalId()
.Property(x => x.Name, "columnName")
.Reference(x => x.Test, "referenceColumnName")
// etc.
.Not.ReadOnly();

Column names are optional. There's no way to set other column options. And ReadOnly is FNH name for mutable attribute.

Monday, February 6, 2012

Mapping-by-Code - Map

The last not yet covered collection type supported in NHibernate 3.2 mapping-by-code is Map. I'll skip all the options that are common with set and bag and refer to its own post. For other collection types, see also the previous post.

Map is NHibernate's name for dictionary, or key-value collection. It is quite a powerful feature. NHibernate allows keys and values to be of different types - either single elements (like strings), components or entities. We can have an entity in the key and string in the value or string in the key and component in the value, etc. Moreover, as with every other collection, map can take part in one-to-many, many-to-many and even many-to-any relationships. There's quite a lot of options.

Mapping for all of these options must be scary, one may think. But not with mapping-by-code. I'm really impressed how easy, convenient and consistent with all the other features the Map mapping is. There's an recurring pattern in mapping-by-code that each nested element in XML has its corresponding options as a separate method parameter. And that's the case for Map, too. There are three basic overloads for Map method:

public void Map<TKey, TElement>(
Expression<Func<TEntity, IDictionary<TKey, TElement>>> property,
Action<IMapPropertiesMapper<TEntity, TKey, TElement>> collectionMapping);

public void Map<TKey, TElement>(
Expression<Func<TEntity, IDictionary<TKey, TElement>>> property,
Action<IMapPropertiesMapper<TEntity, TKey, TElement>> collectionMapping,
Action<ICollectionElementRelation<TElement>> mapping);

public void Map<TKey, TElement>(
Expression<Func<TEntity, IDictionary<TKey, TElement>>> property,
Action<IMapPropertiesMapper<TEntity, TKey, TElement>> collectionMapping,
Action<IMapKeyRelation<TKey>> keyMapping,
Action<ICollectionElementRelation<TElement>> mapping);

Don't be scared. These are just three variants of the same method ordered from the simplest one (with two parameters skipped - it'll have its default values) to the most complete one (with all four parameters). Let's focus on the last one.

The first parameter is - as always - the lambda expression pointing to a generic IDictionary property we are mapping. The second is an obligatory collection mapping - all the standard collection options (described in the post about Bag and Set) are available there. The third one, optional, is to set options for dictionary key mapping and the last one, also optional, is about its value mapping. Here it is, with all its options:

Map(x => x.Features, c =>
{
// standard collection options here
}, k =>
{
k.Element(e =>
{
e.Column("indexColumnName");
// or
e.Column(c =>
{
c.Name("indexColumnName");
// etc...
});

e.Formula("arbitrary SQL expression");
e.Length(10);
e.Type<CustomType>();
});
// or
k.Component(e =>
{
e.Property(x => x.KeyElement);
e.ManyToOne(x => x.OtherKeyElement);
// etc...
});
// or
k.ManyToMany(e =>
{
e.Column("indexColumnName");
// or
e.Column(c =>
{
c.Name("indexColumnName");
// etc...
});

e.ForeignKey("foreignKeyName");
e.Formula("arbitrary SQL expression");
});
}, r =>
{
// one of the following:
r.OneToMany();
r.Element();
r.Component(m => {});
r.ManyToMany();
r.ManyToAny<CommonIdType>(m => {});
});

Let's talk about key and value mappings (third and fourth parameter). In XML, there are plenty of different names for all its options, like map-key, composite-map-key, map-key-many-to-many etc. Mapping-by-code simplifies it drastically. We just need to choose what type of element our key is - either Element (for simple values), Component or ManyToMany (for cases when we have an entity as a key). We are already familiar with all the options inside. The same is for value mapping - we need to choose one of five possible relation types, depending on what do we have as a value in our dictionary. For the description of different relation types, see separate post - all the options are available here, too.

Moreover, the default ConventionModelMapper is smart enough to figure out most options just by looking at our model and in most cases we just don't need to specify the relation types and its options at all.

Fluent NHibernate's equivalent

In Fluent NHibernate, the name "Map" was already used for Property mapping. Instead we have several different methods in HasMany/HasManyToMany chains to be used - AsMap, AsEntityMap, AsSimpleAssociation, AsTernaryAssociation. Pretty hard to figure out what's what.

Mapping for the dictionary value and its options stays the same as in Bag/Set case. I'll focus on mapping different key types.

The first case is when we have simple value as a key - like IDictionary<string, string>:

HasMany(x => x.Dictionary)
.AsMap<string>("keyColumn")
.Element("valueColumn");

Majority of AsMap overloads want me to specify lambda expression pointing from the value to the key and internally use AsIndexedCollection method (designed for List, I believe). These methods seems to assume that key is a part of an object in value, what is strange a bit. In that case we don't really need to have a dictionary and we could just map that collection as a simple bag.

Moreover, FNH is not trying to determine the key type on its own - we need to specify it as a generic parameter in AsMap method explicitly, otherwise we'll end up with int. I also can't see the way to set other key options available in mapping-by-code, i.e. Length or Formula.

The second case I've tried was having a component as a key - and I've failed. I was looking through the Web and the source code itself and I can't see no composite-index equivalent.

Third type of objects allowed as a key is another entity - i.e. IDictionary<Entity, string>. We can map it using AsEntityMap:

HasMany(x => x.Dictionary)
.AsEntityMap()
.Element("valueColumn");

I was looking for any clues when should I use AsTernaryAssociation or AsSimpleAssociation directly, but I don't find any.

To sum things up, dictionary mapping in Fluent NHibernate is a horrible mess. I've found a comment in FNH source code: "I'm not proud of this. The fluent interface for maps really needs to be rethought. But I've let maps sit unsupported for way too long so a hack is better than nothing." Well, personally I'm not sure whether it'll be better in this case. Mapping by code is way much better this time.

Friday, February 3, 2012

Mapping-by-Code - List, Array, IdBag

Time to complete the subject of collection mappings - there are some features unique for lists and idbags that need to be mentioned. I'll skip all the options that are common with set and bag and refer to its own post.

List is an explicitly ordered collection. It has an additional option in the mapping for the index column that keeps the ordering, with the standard Column options mapping inside.

List(x => x.Districts, c =>
{
c.Index(idx =>
{
idx.Base(1);
idx.Column("indexColumnName");
// or
idx.Column(ic =>
{
ic.Name("indexColumnName");
// etc...
});
});
});

There are two other rarely used ordered collections in NHibernate - arrays and primitive arrays. Both are not supported in mapping-by-code. But I don't think it's a big deal.

Another collection type is IdBag. It is generally a bag enriched with additional identity column - useful for many-to-many intermediate tables, when we don't want to have composite primary key there. The only new option in the mapping is Id method, with several options available:

IdBag(x => x.Collection, c =>
{
c.Id(i =>
{
i.Column("idColumn");
i.Generator(Generators.Native);
i.Length(100);
i.Type(new Int32Type());
});
}, r => r.ManyToMany());

Fluent NHibernate's equivalents

As we already know, FNH defines collection mappings as a part of relation mapping chain. I'll skip all the options already covered in the Bag/Set post.

List is mapped using AsList method. There is a possibility to set index column name and type - other DDL options, as well as base attribute are missing.

HasMany(x => x.Users)
.AsList(idx => idx.Column("indexColumnName").Type<int>())

Array is also supported, contrary to mapping-by-code. It has similiar possibilities to the list mapping, the only difference is that we can define index column name by lambda parameter, but it's used only if we don't specify it in the second parameter explicitly.

HasMany(x => x.Users)
.AsArray(x => x.Name, idx => idx.Column("indexColumnName").Type<string>())

Primitive arrays and idbags are not supported.

Thursday, February 2, 2012

Mapping-by-Code - Any

Probably the last relation type supported by NHibernate we have left is any relationship. It is quite an exotic feature. Let's re-use Ayende's model again:

Any lets us to map many-to-one relationship that has entities of different types on the "one" side. There's no foreign keys defined on the database side and the relation logic is maintained on the object level only. To make it work, we need to tell NHibernate what types of entities we expect and how to distinguish it. Here's how to do it in mapping-by-code, with all the options available:

Any(x => x.Payment, typeof(long), m =>
{
m.IdType<long>();
m.MetaType<string>();
m.MetaValue("CreditCard", typeof(CreditCardPayment));
m.MetaValue("Wire", typeof(WirePayment));

m.Columns(id =>
{
id.Name("PaymentId");
id.NotNullable(true);
// etc...
}, classRef =>
{
classRef.Name("PaymentType");
classRef.NotNullable(true);
// etc...
});

m.Access(Accessor.Field);
m.Lazy(true);
m.Cascade(Cascade.Persist);
m.Index("payment_idx");
m.Insert(true);
m.Update(true);
m.OptimisticLock(true);
});

The first parameter is - as always - a lambda pointing to the mapped property. The second defines the common type for identifiers of all entities at the other side. Third one is for mapping options, which are pretty similiar to already mentioned ManyToAny relationship.

Inside the configuration we need to define properties for two columns - one to keep the other entity identifier, second to keep its discriminating value. We do it using Columns method's parameters. Later we have to specify the type of discriminator using MetaType method and its generic argument - string is good here. We can also specify the common type of identifiers using IdType method, but we've already did it in Any second parameter (I think that this method is useless here). The last thing we need to do is to define the list of entity types that are allowed at other side of the relation and its corresponding discriminator values. In order to do this, we call MetaValue method - its first parameter is the discriminator value, second is the type. There are also several standard options available, like Lazy and Cascade.

Fluent NHibernate's equivalent

Contrary to many-to-any, any is supported well in Fluent NHibernate.

ReferencesAny(x => x.Test)
.IdentityType<long>()
.MetaType<string>()
.AddMetaValue<CreditCardPayment>("CreditCard")
.AddMetaValue<WirePayment>("Wire")
.EntityIdentifierColumn("PaymentId")
.EntityTypeColumn("PaymentType")
.Access.Field()
.LazyLoad()
.Cascade.All()
.Insert()
.Update()
.OptimisticLock();

There is no Index method and we can't set options other than name for database columns. Apart from that, the rest is pretty clear and easy.


The next post in Ayende's series was about many-to-any, but I've covered it within collections and relation types, so I'm going to skip it.

Tuesday, January 31, 2012

Mapping-by-Code - Join

We have previously explored the one-to-one mapping, which lets us create 1:1 association in the database, but there is actually another way to map several tables to an object model. We aren't constrained by the database model, and we can merge several tables into a single entity. We do that using the <join> element. It can be mapped with mapping-by-code using Join method pretty easily:

Join("table_name", j =>
{
// join options
j.Table("table_name");
j.Schema("schemaName");
j.Catalog("catalogName");

j.Fetch(FetchKind.Join); // or .Select
j.Inverse(true);
j.Optional(true);

j.Key(k =>
{
k.Column("columnName");
// or
k.Column(c =>
{
c.Name("columnName");
// etc...
});

k.ForeignKey("foreignKeyName");
k.NotNullable(true);
k.OnDelete(OnDeleteAction.Cascade); // or .NoAction
k.PropertyRef(x => x.Name);
k.Unique(true);
k.Update(true);
});

j.Loader("customLoader");
j.SqlInsert("custom SQL");
j.SqlUpdate("custom SQL");
j.SqlDelete("custom SQL");
j.Subselect("custom SQL");

// joined element mappings
j.Property(x => x.MayorName);
// etc...
});

The first parameter, named mysteriously splitGroupId, is an identifier serving by default as the joined table name. The second parameter is used both for join options and mapping the joined elements.

The Key method is an equivalent of XML <key> element, that is required in join mapping. In mapping-by-code it is not required, default convention can handle it. But in case we want to customize anything about the foreign key and its database column, we have standard options available there. All the other XML mapping features are available, too - it's pretty easy to figure out as all its names matches XML attributes or elements names.

The only missing thing, as always in case of custom SQL queries, is the possibility to set up checking the value returned by the query - an equivalent for check attribute in custom queries XML elements.

Fluent NHibernate equivalent

Join mapping in Fluent NHibernate is very similiar to mapping-by-code. The first parameter of Join method is the joined table name, the second are for other options and joined element mappings.

Join("table_name", j =>
{
// join options
j.Table("table_name"); // void
j.Schema("schemaName")
.Catalog("catalogName")
.Fetch.Join() // or .Select()
.Inverse()
.Optional()
.KeyColumn("columnName");
j.SqlInsert("custom SQL").Check.RowCount();
j.SqlUpdate("custom SQL").Check.None();
j.SqlDelete("custom SQL");
j.Subselect("custom SQL");

// joined element mappings
j.Map(x => x.Name);
// etc...
});

There are few options missing - the only thing we can define about the foreign key column is its name - using KeyColumn method. The strange thing is that Table method returns void thus it's not chainable.

Monday, January 30, 2012

Mapping-by-Code - OneToOne

Moving on with relation types in NHibernate - we haven't talked about <one-to-one> yet. The name suggests that it's designed for 1:1 relationships and this is not quite correct. 1:1 relationships can be mapped simply using many-to-one with unique constraint. One-to-one is designed specifically for making that many-to-one relationship with unique constraint bidirectional.

This kind of relation is mapped using many-to-one on the side that owns the relationship (in terms of having foreign key column in the database) and one-to-one on the second side. Note that at one-to-one side there's no column at the database level - the relationship from "one" side is "virtual", maintained only by NHibernate.

In mapping-by-code we're mapping it using OneToOne method. It has two parameters. The first one is the lambda pointing to the mapped property, as always. The second one are the options.

OneToOne(x => x.User, m =>
{
m.Cascade(Cascade.Persist);
m.Constrained(true);
m.Lazy(LazyRelation.Proxy); // or .NoProxy, .NoLazy
m.PropertyReference(typeof(User).GetPropertyOrFieldMatchingName("OtherSideProperty"));
m.OptimisticLock(true);
m.Formula("arbitrary SQL expression");
m.Access(Accessor.Field);
});

Two things to note here. The first one is the lack of possibility to choose the fetch mode and foreign key name. The second one is the cumbersome construct needed to map property-ref option - the method is called PropertyReference instead of standard PropertyRef and its parameter is MethodInfo-typed instead of standard lambda expression or string at least. It looks like the feature went to production before it was finished.

Fluent NHibernate's equivalent

Fluent NHibernate's name for one-to-one is HasOne. I think this is the most often misused method in FNH as it looks like a natural sibling for HasMany and HasManyToMany and it seems to be a good choice for many-to-one mapping (which turns out to be mapped by References method). A bit messy, isn't it?

Here's how to use it:

HasOne(x => x.User)
.Cascade.SaveUpdate()
.Constrained()
.LazyLoad(Laziness.Proxy) // or .NoProxy, .False
.PropertyRef(x => x.OtherSideProperty)
.Access.Field()
.Class<CustomType>()
.Fetch.Join() // or .Select(), .Subselect()
.ForeignKey("foreignKeyName");

Apart for the name issue, it's a bit better than in mapping-by-code this time. The only option not available here is formula.