NHibernate – Executable DML

time to read 4 min | 712 words

This is a new feature of NHibernate that Fabio has recently ported. Using the same model that I have talked about before:

image

With the following schema:

image

The feature is basically this, NHibernate can now execute set based operation on your model. This include all Data Modification Language operations, so we are talking about Update, Insert and Delete. Let us make things a bit interesting and talk about the following statement, which hopefully will make things clearer:

s.CreateQuery("update Owner o set o.Name = 'a' where o.Name = 'b'")
    .ExecuteUpdate();

Executing this code will make NHibernate execute the following SQL statements:

image

image

image

image

image

image

As you can see, we have executed a very simple query against the model, which translate to a fairly complex data model (needing to update three separate tables. We can also see that we are doing significant effort to maintain the illusion of a single query (that is why we need the temp table here).

But we are not limited to just updates, we can also do deletes:

s.CreateQuery("delete Owner o where o.Name = 'b'")
    .ExecuteUpdate();

Which result in:

image

image

image

image

image

image

I think that by now you are already familiar with the pattern :-)

As for insert statements, they are supported as well, but there are some limitations. In particular, you have to use an identifiers generation strategy that can generate identifiers in the database (sequence or identity), and there are some limitation on how you can make this work in several complex hierarchies. Using a simple Table Per Class, the following HQL works:

s.CreateQuery("insert into Individual (Name, Email) select i.Name, i.Email from Individual i")
    .ExecuteUpdate();

And generates:

image

All in all, this is a really awesome feature.

Thanks, Fabio.