Saturday, 30 January 2010

NHibernate Generated SQL

The other day I needed to find the SQL generated by NHibernate to be displayed at runtime - the 'displayed at runtime' part being the trickiest, obviously I could set the show_sql property to log the sql but that wasn't what was required.

A search around the internet yielded nothing so I looked into the NHibernate assembly and found the NHibernate.Engine.Query.HqlPlan class which contained a property, SqlStrings, which suggested it would do exactly as I needed. And so it turned out, I instantiated the class like so:

new NHibernate.Engine.Query.HqlPlan(hqlQueryString, false, new System.Collections.Generic.Dictionary(), factoryImplementor);

and sure enough the SqlStrings property contained the SQL to be executed for 'hqlQueryString'.

No comments: