There was an interesting thread on the NHibernate users mailing list this week where Fabio Maulo advised the use of NHibernate named queries to a user who was experiencing severe performance issues with a bulk update scenario.

This is great stuff, and I have ignored named queries almost completely in the past.

using(ISession s = OpenSession()) {
using (ITransaction tx = s.BeginTransaction())
{
IQuery sql = s.GetNamedQuery("native-delete-car").SetString(0, "Kirsten");
sql.ExecuteUpdate();
tx.Commit();
}
}


That is Fabio's example of executing the named query.  This was the mapping for the query:

<sql-query name="native-delete-car">
        <synchronize table="VEHICLE"/>
        delete from VEHICLE where Owner = ?
</sql-query>

*As Fabio so helpfully pointed out in my over eagerness posting this I ignored that this is indeed a SQL statement.  The sql-query element name should've given it away I think :). 

Here's an example of an HQL one:

<query name="delete-car">
   <![CDATA[
       delete Vehicle v where v.Owner = :owner
   ]]>
</query>

note: ExecuteUpdate is currently not supported for HQL queries.  This was the only JIRA I could find about this issue.  Looks like we're waiting on Ayende to work some magic before we have this support.

UPDATE: NH-1036 is fixed and closed!  This now works.

It may not look very ORMish.  Some of you may be saying, "What's the point of using an ORM at all if we're just writing SQL."  Well, that's not SQL, that's HQLHQL is not as nice as the criteria API, but it's a step above straight SQL.  Also, there are some things you can express with HQL that you can not express with the Criteria API.

Castle ActiveRecord users are not left out in the cold either.  ActiveRecord can also cleanly express named queries.  Check out the castle page on ActiveRecordBaseQuery (here).

Also, the prolific Oren Eini has a post (here) about named queries.