我如何让NHibernate只生成SQL而不执行它?
我知道如何使用show_sql
configuration选项在运行时将SQL日志logging到log4net / NLog /跟踪窗口。
我正在寻找的是一种给NHibernate的Query<T>()
检索生成的SQL的方法。
我已经浏览了Persister类,驱动程序,不同的拦截器和事件。 有很多地方可以看,甚至缩小我的search会有很大的帮助。
您可以使用以下方法获取生成的sql查询而不执行:
对于NHibernate.Linq查询:
public String GetGeneratedSql(System.Linq.IQueryable queryable, ISession session) { var sessionImp = (ISessionImplementor) session; var nhLinqExpression = new NhLinqExpression(queryable.Expression, sessionImp.Factory); var translatorFactory = new ASTQueryTranslatorFactory(); var translators = translatorFactory.CreateQueryTranslators(nhLinqExpression, null, false, sessionImp.EnabledFilters, sessionImp.Factory); return translators[0].SQLString; }
对于条件查询:
public String GetGeneratedSql(ICriteria criteria) { var criteriaImpl = (CriteriaImpl) criteria; var sessionImpl = (SessionImpl) criteriaImpl.Session; var factory = (SessionFactoryImpl) sessionImpl.SessionFactory; var implementors = factory.GetImplementors(criteriaImpl.EntityOrClassName); var loader = new CriteriaLoader((IOuterJoinLoadable) factory.GetEntityPersister(implementors[0]), factory, criteriaImpl, implementors[0], sessionImpl.EnabledFilters); return loader.SqlString.ToString(); }
对于QueryOver查询:
public String GetGeneratedSql(IQueryOver queryOver) { return GetGeneratedSql(queryOver.UnderlyingCriteria); }
对于Hql查询:
public String GetGeneratedSql(IQuery query, ISession session) { var sessionImp = (ISessionImplementor)session; var translatorFactory = new ASTQueryTranslatorFactory(); var translators = translatorFactory.CreateQueryTranslators(query.QueryString, null, false, sessionImp.EnabledFilters, sessionImp.Factory); return translators[0].SQLString; }
基于NHibernate 3.4版本,linqexpression式的方法是:
public String GetGeneratedSql(System.Linq.IQueryable queryable, ISession session) { var sessionImp = (ISessionImplementor)session; var nhLinqExpression = new NhLinqExpression(queryable.Expression, sessionImp.Factory); var translatorFactory = new ASTQueryTranslatorFactory(); var translators = translatorFactory.CreateQueryTranslators(nhLinqExpression.Key, nhLinqExpression, null, false, sessionImp.EnabledFilters, sessionImp.Factory); var sql = translators.First().SQLString; var formamttedSql = FormatStyle.Basic.Formatter.Format(sql); int i = 0; var map = ExpressionParameterVisitor.Visit(queryable.Expression, sessionImp.Factory).ToArray(); formamttedSql = Regex.Replace(formamttedSql, @"\?", m => map[i++].Key.ToString().Replace('"', '\'')); return formamttedSql; }