With Nhierbate, it is seldom necessary to write native SQL statements, which are sometimes bad for SQL tuning because SQL statements are always not visible. Hence the idea of letting nhibernate output the SQL statements generated by it so that it can be tuned later.
one, output SQL statements on the console
In the console program, to see the SQL statements generated by NHibernate, the method is very simple, only need to change the configuration file is ok.
<name= "Show_sql">true</Property> <name= "Format_sql">true</ Property>
The first parameter is used to configure whether to output SQL statements to the console.
The second parameter is used to format the output SQL statement for easy viewing.
The difference between setting only the first and two settings is as follows:
Show only unformatted:
After formatting:
The above method is the configuration console display, if not in the console execution, is a Web application.
Web program output SQL statement to "Debug window"
The way the Web program outputs is also not difficult.
The first step: Write a class that inherits from Emptyinterceptor and overrides the Onpreparestatement method.
Public class sqlwatcher:emptyinterceptor{ publicoverride NHibernate.SqlCommand.SqlString Onpreparestatement (NHibernate.SqlCommand.SqlString sql) { System.Diagnostics.Debug.WriteLine (" SQL statement:" + sql") ; return Base . Onpreparestatement (SQL);} }
Step two: When creating opensession, use objects of this class as parameters to pass in
ISession session = sessionfactory.opensession (new sqlwatcher ());
The effect is as follows:
Reference: HTTP://WWW.MASHANGPIAO.NET/ARTICLE/CONTENT/53
NHibernate Output SQL statements