Thursday, September 20, 2012

Getting SQL from HQL


I havent had the need for this yet, but thought it might be handy to keep it noted.


String hql = "select a.id from Animal a";

ISessionImplementor sessionImp = session.GetSessionImplementation(); 
IQueryTranslatorFactory factory = new ASTQueryTranslatorFactory();
IQueryTranslator[] translators = factory.CreateQueryTranslators(hql, null, false, sessionImp.EnabledFilters, sessionImp.Factory);


if (translators == null || translators.Count() == 0)
   throw new Exception("Could not create the required SQL from HQL");


//Possible should join the sql statements separated by ";"
return translators[0].SQLString;