Put together a very simple database using Hibernate, but notice that quite often I get the Glassdoor server error telling me "Too Many Connections".
I assume this is because I'm not correctly closing my connections when I update/add/remove database items.
Here's an example of what I do in my updateEntry.jsp-- any blantant issues? If not I can post my removeEntry.jsp and newEntry.jsp:
<%#page import="java.util.Date" %>
<%#page import="org.hibernate.Session" %>
<%#page import="org.hibernate.SessionFactory" %>
<%#page import="org.hibernate.Transaction" %>
<%#page import="org.hibernate.cfg.Configuration" %>
<%#page import="java.util.Date" %>
<%
String nId = request.getParameter("pID");
String naddress = request.getParameter("pAddress");
String nstatus = request.getParameter("pStatus");
String nassigned = request.getParameter("pAssigned");
String nnote = request.getParameter("pNote");
if (!naddress.equals("undefined"))
{
// This step will read hibernate.cfg.xml and prepare hibernate for use
org.hibernate.SessionFactory sessionFactory1 = new org.hibernate.cfg.Configuration().configure().buildSessionFactory();
org.hibernate.Session session1 = sessionFactory1.openSession();
org.hibernate.Query query1 = session1.createQuery("update Leads set Address = :naddr where Id = :nid");
query1.setParameter("nid", nId);
query1.setParameter("naddr", naddress);
query1.executeUpdate();
//out.println("Update successfully with: " + naddress);
// Actual contact insertion will happen at this step
session1.flush();
session1.close();
}
if (!nstatus.equals("undefined"))
{
// This step will read hibernate.cfg.xml and prepare hibernate for use
org.hibernate.SessionFactory sessionFactory2 = new org.hibernate.cfg.Configuration().configure().buildSessionFactory();
org.hibernate.Session session2 = sessionFactory2.openSession();
org.hibernate.Query query2 = session2.createQuery("update Leads set Status = :nstatus where Id = :nid");
query2.setParameter("nid", nId);
query2.setParameter("nstatus", nstatus);
query2.executeUpdate();
//out.println("Update successfully with: " + nstatus);
// Actual contact insertion will happen at this step
session2.flush();
session2.close();
}
if (!nassigned.equals("undefined"))
{
// This step will read hibernate.cfg.xml and prepare hibernate for use
org.hibernate.SessionFactory sessionFactory3 = new org.hibernate.cfg.Configuration().configure().buildSessionFactory();
org.hibernate.Session session3 = sessionFactory3.openSession();
org.hibernate.Query query3 = session3.createQuery("update Leads set Assigned = :nassigned where Id = :nid");
query3.setParameter("nid", nId);
query3.setParameter("nassigned", nassigned);
query3.executeUpdate();
//out.println("Update successfully with: " + nassigned);
// Actual contact insertion will happen at this step
session3.flush();
session3.close();
}
if (!nnote.equals("undefined"))
{
// This step will read hibernate.cfg.xml and prepare hibernate for use
org.hibernate.SessionFactory sessionFactory4 = new org.hibernate.cfg.Configuration().configure().buildSessionFactory();
org.hibernate.Session session4 = sessionFactory4.openSession();
org.hibernate.Query query4 = session4.createQuery("update Leads set Notes = :nnote where Id = :nid");
query4.setParameter("nid", nId);
query4.setParameter("nnote", nnote);
query4.executeUpdate();
//out.println("Update successfully with: " + nnote);
// Actual contact insertion will happen at this step
session4.flush();
session4.close();
}
%>
You should not initialize hibernate within the JSP, you just initialize once when the context start.
Normally you would put the hibernate factory initialization upon context initialization, then you should get the session from the factory once at the start of every request.
#WebListener
public class HibernateListener implements ServletContextListener {
public static final String ENTITY_MANAGER = "entity.manager";
public void contextInitialized(ServletContextEvent evt) {
SessionFactory sessionFactory = new Configuration()
.configure().buildSessionFactory();
evt.getServletContext()
.setAttribute(ENTITY_MANAGER, sessionFactory);
}
public void contextDestroyed(ServletContextEvent evt) {
SessionFactory sessionFactory = (SessionFactory) evt.getServletContext()
.getAttribute(ENTITY_MANAGER);
sessionFactory.close();
}
}
Then you could get the session picking the entityManager from the servletContext.
<% SessionFactory factory =(SessionFactory) session.getServletContext()
.getAttribute(HibernateListener.ENTITY_MANAGER); %>
I think you should carefully read Hibernate Quickstart Guide
Related
I'm still fairly new to the whole libgit2 and libgit2sharp codebases, but I've been trying to tackle the issue of In-Memory repositories and Refdb storage of references.
I've gotten everything almost working in my new branch:
Create the In-Memory repository and attach Refdb and Odb instance to it.
Create initial commit and set the reference for refs/heads/master.
Create the second commit...
The problem I run into now is updating refs/heads/master to the second commit. The UpdateTarget call to refs/heads/master runs into an error in git_reference_set_target:
LibGit2Sharp.NameConflictException : config value 'user.name' was not found
at LibGit2Sharp.Core.Ensure.HandleError(Int32 result) in \libgit2sharp\LibGit2Sharp\Core\Ensure.cs:line 154
at LibGit2Sharp.Core.Ensure.ZeroResult(Int32 result) in \libgit2sharp\LibGit2Sharp\Core\Ensure.cs:line 172
at LibGit2Sharp.Core.Proxy.git_reference_set_target(ReferenceHandle reference, ObjectId id, String logMessage) in \libgit2sharp\LibGit2Sharp\Core\Proxy.cs:line 2042
at LibGit2Sharp.ReferenceCollection.UpdateDirectReferenceTarget(Reference directRef, ObjectId targetId, String logMessage) in \libgit2sharp\LibGit2Sharp\ReferenceCollection.cs:line 476
at LibGit2Sharp.ReferenceCollection.UpdateTarget(Reference directRef, ObjectId targetId, String logMessage) in \libgit2sharp\LibGit2Sharp\ReferenceCollection.cs:line 470
at LibGit2Sharp.ReferenceCollection.UpdateTarget(Reference directRef, String objectish, String logMessage) in \libgit2sharp\LibGit2Sharp\ReferenceCollection.cs:line 498
at LibGit2Sharp.ReferenceCollection.UpdateTarget(String name, String canonicalRefNameOrObjectish, String logMessage) in \libgit2sharp\LibGit2Sharp\ReferenceCollection.cs:line 534
at LibGit2Sharp.ReferenceCollection.UpdateTarget(String name, String canonicalRefNameOrObjectish) in \libgit2sharp\LibGit2Sharp\ReferenceCollection.cs:line 565
at LibGit2Sharp.Tests.RepositoryFixture.CanCreateInMemoryRepositoryWithBackends() in \libgit2sharp\LibGit2Sharp.Tests\RepositoryFixture.cs:line 791
I have not been able to debug down into the libgit2 level, but from what I can tell the issue is in git_reference_create_matching call to git_reference__log_signature.
Is there a call I am missing that can update a reference in a Bare repo that doesn't require a signature? If any libgit2 guys know of how to do this in libgit2, I can implement it on the C# side.
As a test, I created two unit tests that perform the same actions In-Memory and on disk, and the In-Memory fails when calling UpdateTarget after creating the second commit. This follows the code on the wiki:
private Commit CreateCommit(Repository repository, string fileName, string content, string message = null)
{
if (message == null)
{
message = "i'm a commit message :)";
}
Blob newBlob = repository.ObjectDatabase.CreateBlobFromContent(content);
// Put the blob in a tree
TreeDefinition td = new TreeDefinition();
td.Add(fileName, newBlob, Mode.NonExecutableFile);
Tree tree = repository.ObjectDatabase.CreateTree(td);
// Committer and author
Signature committer = new Signature("Auser", "auser#example.com", DateTime.Now);
Signature author = committer;
// Create binary stream from the text
return repository.ObjectDatabase.CreateCommit(
author,
committer,
message,
tree,
repository.Commits,
true);
}
[Fact]
public void CanCreateRepositoryWithoutBackends()
{
SelfCleaningDirectory scd = BuildSelfCleaningDirectory();
Repository.Init(scd.RootedDirectoryPath, true);
ObjectId commit1Id;
using (var repository = new Repository(scd.RootedDirectoryPath))
{
Commit commit1 = CreateCommit(repository, "filePath.txt", "Hello commit 1!");
commit1Id = commit1.Id;
repository.Refs.Add("refs/heads/master", commit1.Id);
Assert.Equal(1, repository.Commits.Count());
Assert.NotNull(repository.Refs.Head);
Assert.Equal(1, repository.Refs.Count());
}
using (var repository = new Repository(scd.RootedDirectoryPath))
{
Commit commit2 = CreateCommit(repository, "filePath.txt", "Hello commit 2!");
Assert.Equal(commit1Id, commit2.Parents.First().Id);
repository.Refs.UpdateTarget("refs/heads/master", commit2.Sha);
Assert.Equal(2, repository.Commits.Count());
Assert.Equal(1, repository.Refs.Count());
Assert.NotNull(repository.Refs.Head);
Assert.Equal(commit2.Sha, repository.Refs.Head.ResolveToDirectReference().TargetIdentifier);
}
}
[Fact]
public void CanCreateInMemoryRepositoryWithBackends()
{
OdbBackendFixture.MockOdbBackend odbBackend = new OdbBackendFixture.MockOdbBackend();
RefdbBackendFixture.MockRefdbBackend refdbBackend = new RefdbBackendFixture.MockRefdbBackend();
ObjectId commit1Id;
using (var repository = new Repository())
{
repository.Refs.SetBackend(refdbBackend);
repository.ObjectDatabase.AddBackend(odbBackend, 5);
Commit commit1 = CreateCommit(repository, "filePath.txt", "Hello commit 1!");
commit1Id = commit1.Id;
repository.Refs.Add("refs/heads/master", commit1.Id);
Assert.Equal(1, repository.Commits.Count());
Assert.NotNull(repository.Refs.Head);
Assert.Equal(commit1.Sha, repository.Refs.Head.ResolveToDirectReference().TargetIdentifier);
// Emulating Git, repository.Refs enumerable does not include the HEAD.
// Thus, repository.Refs.Count will be 1 and refdbBackend.References.Count will be 2.
Assert.Equal(1, repository.Refs.Count());
Assert.Equal(2, refdbBackend.References.Count);
}
using (var repository = new Repository())
{
repository.Refs.SetBackend(refdbBackend);
repository.ObjectDatabase.AddBackend(odbBackend, 5);
Commit commit2 = CreateCommit(repository, "filePath.txt", "Hello commit 2!");
Assert.Equal(commit1Id, commit2.Parents.First().Id);
//repository.Refs.UpdateTarget(repository.Refs["refs/heads/master"], commit2.Id);
//var master = repository.Refs["refs/heads/master"];
//Assert.Equal(commit1Id.Sha, master.TargetIdentifier);
repository.Refs.UpdateTarget("refs/heads/master", commit2.Sha); // fails at LibGit2Sharp.Core.Proxy.git_reference_set_target(ReferenceHandle reference, ObjectId id, String logMessage)
//repository.Refs.Add("refs/heads/master", commit2.Id); // fails at LibGit2Sharp.Core.Proxy.git_reference_create(RepositoryHandle repo, String name, ObjectId targetId, Boolean allowOverwrite, String logMessage)
Assert.Equal(2, repository.Commits.Count());
Assert.Equal(1, repository.Refs.Count());
Assert.NotNull(repository.Refs.Head);
Assert.Equal(commit2.Sha, repository.Refs.Head.ResolveToDirectReference().TargetIdentifier);
}
}
I am trying to use the TFS API to rollback a changeset.
I tried using all Workspace.Rollback methods but the action does nothing (The GetStatus returned says NoActionNeeded:true).
Has anyone managed to get this to work and can send a working code sample?
From the documentation of the method:
public GetStatus Rollback(
string[] paths,
RecursionType recursion,
VersionSpec itemSpecVersion,
VersionSpec versionFrom,
VersionSpec versionTo,
LockLevel lockLevel,
RollbackOptions options,
string[] itemAttributeFilters
)
I do not understand what the parameter VersionSpec itemSpecVersion means.
It says 'The version spec that identifies the item to which the user is referring.' but then how does it differ from the parameter versionFrom?
What should I pass as the itemAttributeFilters (the last paramter)?
You can rollback changeset programmatically with the following code:
TfsTeamProjectCollection tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("tfsCollectionURL"));
VersionControlServer vcs = (VersionControlServer)tpc.GetService(typeof(VersionControlServer));
string workingDirectory = #"localPath";
string[] workigDnirectoryArr = new string[] { workingDirectory };
Workspace ws = vcs.GetWorkspace("$/serverPath");
int fromCS = 456; //changesetid
int toCS = 495; //changesetid
VersionSpec versionSpecFrom = new ChangesetVersionSpec(fromCS);
VersionSpec versionSpecTo = new ChangesetVersionSpec(toCS);
var status = ws.Rollback(workigDnirectoryArr, RecursionType.None,null, versionSpecFrom, versionSpecTo,LockLevel.None,RollbackOptions.None,null);
I am trying to connect to oracle DB .
I want to retrieve list of passwords from data base using the authentication query. Here is my sample shiro.ini file:
# password matcher
passwordMatcher = org.apache.shiro.authc.credential.PasswordMatcher
passwordService = org.apache.shiro.authc.credential.DefaultPasswordService
passwordMatcher.passwordService = $passwordService
# datasource
ds = oracle.jdbc.pool.OracleDataSource
ds.URL = jdbc:oracle:thin:#matrix-oracle11g:1521:dev11g
ds.user = cit1am
ds.password = cit1
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.authenticationQuery = SELECT USR_PSWD FROM USR
jdbcRealm.credentialsMatcher = $passwordMatcher
jdbcRealm.dataSource = $ds
securityManager.realms = $jdbcRealm
[users]
[roles]
[urls]
Sample code snippet of login:
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject currentUser = SecurityUtils.getSubject();
// Do some stuff with a Session (no need for a web or EJB container!!!)
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
try{
// let's login the current user so we can check against roles and permissions:
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken("cit1am", "cit1") ;
token.setRememberMe(true);
try {
currentUser.login(token); //problem occurs here
log.info("inside try block ==========>>" );
}
catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
}
I am getting following error:
[main] ERROR org.apache.shiro.realm.jdbc.JdbcRealm - There was a SQL error while authenticating user [cit1am]
java.sql.SQLException: Invalid column index
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:199)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:263)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:271)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:445)
Please suggest what i am doing wrong?
After debugging more i found issue with my code and sql query in .ini file.
I changed following in .INI file
jdbcRealm.authenticationQuery = SELECT USR_PSWD FROM USR where USR_NM = ?
Also commented
#cm = org.apache.shiro.authc.credential.Sha256CredentialsMatcher
#jdbcRealm.credentialsMatcher = $cm and removedconfiguration related to password matcher
I also removed role and permission check from java code.
As i have just started with shrio it's bit difficult to understand flow at start.
Though it can help some one in future.
Thanks
I have this code for filling DB, but after finish, DB is still empty. Only number in hibernate_unique_key table is higher.
The next thing which is interesting is, that during debugging instances has id, after save, but not like 1,2,3... but very high like 60083, 60084, ... etc. (It not seems normal, because there is only several rows for save).
Before that, there was some problems with references and so on, but now there is no error message or exception.
code is there:
using System;
using NHibernate.Cfg;
using SharpArch.Data.NHibernate;
using LaboratorniMetody.Data.NHibernateMaps;
using SharpArch.Core.PersistenceSupport;
using LaboratorniMetody.Core;
namespace LaboratorniMetody.FillSchema
{
class Program
{
private static Configuration configuration;
static void Main(string[] args)
{
configuration = NHibernateSession.Init(new SimpleSessionStorage(), new String[] { "LaboratorniMetody.Data" },
new AutoPersistenceModelGenerator().Generate(),
"../../../../app/LaboratorniMetody.Web/NHibernate.config");
IRepository<Laboratory> LaboratoryRepository = new Repository<Laboratory>();
Laboratory Laboratory1 = new Laboratory() { Name = "Hematologie" };//Method
Laboratory l = LaboratoryRepository.SaveOrUpdate(Laboratory1);
Laboratory Laboratory2 = new Laboratory() { Name = "Patologie" };//Method
LaboratoryRepository.SaveOrUpdate(Laboratory2);
Laboratory Laboratory3 = new Laboratory() { Name = "Laboratoře" };//Method
LaboratoryRepository.SaveOrUpdate(Laboratory3);
}
}
}
I use DB schema genereted by NUnit from Project.Core classes.
Do you have any ideas where i should find problem? I have 2 very similar project which working with no problem. I Copyed this code from one of them and there is practicly no differents (except DB model and so on.)
You need to do your changes in a transaction and commit the transaction afterwards.
using(var tx = NHibernateSession.Current.BeginTransaction())
{
IRepository<Laboratory> LaboratoryRepository = new Repository<Laboratory>();
Laboratory Laboratory1 = new Laboratory() { Name = "Hematologie" };//Method
Laboratory l = LaboratoryRepository.SaveOrUpdate(Laboratory1);
Laboratory Laboratory2 = new Laboratory() { Name = "Patologie" };//Method
LaboratoryRepository.SaveOrUpdate(Laboratory2);
Laboratory Laboratory3 = new Laboratory() { Name = "Laboratoře" };//Method
LaboratoryRepository.SaveOrUpdate(Laboratory3);
tx.Commit();
}
I advise to look at the SharpArchContrib project wiki, which has some samples on using SharpArch in a windows app/service and how to use Transaction attributes from there.
https://github.com/sharparchitecture/Sharp-Architecture-Contrib/wiki/
How do I view the SQL that is generated by nHibernate? version 1.2
You can put something like this in your app.config/web.config file :
in the configSections node :
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
in the configuration node :
<log4net>
<appender name="NHibernateFileLog" type="log4net.Appender.FileAppender">
<file value="logs/nhibernate.txt" />
<appendToFile value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n" />
</layout>
</appender>
<logger name="NHibernate.SQL" additivity="false">
<level value="DEBUG"/>
<appender-ref ref="NHibernateFileLog"/>
</logger>
</log4net>
And don't forget to call
log4net.Config.XmlConfigurator.Configure();
at the startup of your application, or to put
[assembly: log4net.Config.XmlConfigurator(Watch=true)]
in the assemblyinfo.cs
In the configuration settings, set the "show_sql" property to true.
I am a bit late I know, but this does the trick and it is tool/db/framework independent.
Instead of those valid options, I use NH Interceptors.
At first, implement a class which extends NHibernate.EmptyInterceptor and implements NHibernate.IInterceptor:
using NHibernate;
namespace WebApplication2.Infrastructure
{
public class SQLDebugOutput : EmptyInterceptor, IInterceptor
{
public override NHibernate.SqlCommand.SqlString
OnPrepareStatement(NHibernate.SqlCommand.SqlString sql)
{
System.Diagnostics.Debug.WriteLine("NH: " + sql);
return base.OnPrepareStatement(sql);
}
}
}
Then, just pass an instance when you open your session. Be sure to do it only when in DEBUG:
public static void OpenSession() {
#if DEBUG
HttpContext.Current.Items[SessionKey] = _sessionFactory.OpenSession(new SQLDebugOutput());
#else
HttpContext.Current.Items[SessionKey] = _sessionFactory.OpenSession();
#endif
}
And that's it.
From now on, your sql commands like these...
var totalPostsCount = Database.Session.Query<Post>().Count();
var currentPostPage = Database.Session.Query<Post>()
.OrderByDescending(c => c.CreatedAt)
.Skip((page - 1) * PostsPerPage)
.Take(PostsPerPage)
.ToList();
.. are shown straight in your Output window:
NH: select cast(count(*) as INT) as col_0_0_ from posts post0_
NH:select post0_.Id as Id3_, post0_.user_id as user2_3_, post0_.Title as
Title3_, post0_.Slug as Slug3_, post0_.Content as Content3_,
post0_.created_at as created6_3_, post0_.updated_at as updated7_3_,
post0_.deleted_at as deleted8_3_ from posts post0_ order by
post0_.created_at desc limit ? offset ?
In the configuration settings, set the "show_sql" property to true.
This will cause the SQL to be output in NHibernate's logfiles courtesy of log4net.
Use sql server profiler.
EDIT (1 year later): As #Toran Billups states below, the NHibernate profiler Ayende wrote is very very cool.
You can also try NHibernate Profiler (30 day trial if nothing else). This tool is the best around IMHO.
This will not only show the SQL generated but also warnings/suggestions/etc
There is a good reference for NHibernate logging at: How to configure Log4Net for use with NHibernate. It includes info on logging all NHibernate-generated SQL statements.
Nhibernate Profiler is an option, if you have to do anything serious.
If you're using SQL Server (not Express), you can try SQL Server Profiler.
Or, if you want to show the SQL of a specific query, use the following method (slightly altered version of what suggested here by Ricardo Peres) :
private String NHibernateSql(IQueryable queryable)
{
var prov = queryable.Provider as DefaultQueryProvider;
var session = prov.Session as ISession;
var sessionImpl = session.GetSessionImplementation();
var factory = sessionImpl.Factory;
var nhLinqExpression = new NhLinqExpression(queryable.Expression, factory);
var translatorFactory = new NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory();
var translator = translatorFactory.CreateQueryTranslators(nhLinqExpression, null, false, sessionImpl.EnabledFilters, factory).First();
var sql = translator.SQLString;
var parameters = nhLinqExpression.ParameterValuesByName;
if ( (parameters?.Count ?? 0) > 0)
{
sql += "\r\n\r\n-- Parameters:\r\n";
foreach (var par in parameters)
{
sql += "-- " + par.Key.ToString() + " - " + par.Value.ToString() + "\r\n";
}
}
return sql;
}
and pass to it a NHibernate query, i.e.
var query = from a in session.Query<MyRecord>()
where a.Id == "123456"
orderby a.Name
select a;
var sql = NHibernateSql(query);
You are asking only for viewing; but this answer explains how to log it to file. Once logged, you can view it in any text editor.
Latest versions of NHibernate support enabling logging through code. Following is the sample code that demonstrates this. Please read the comments for better understanding.
Configuration configuration = new Configuration();
configuration.SetProperty(NHibernate.Cfg.Environment.Dialect, ......);
//Set other configuration.SetProperty as per need
configuration.SetProperty(NHibernate.Cfg.Environment.ShowSql, "true"); //Enable ShowSql
configuration.SetProperty(NHibernate.Cfg.Environment.FormatSql, "true"); //Enable FormatSql to make the log readable; optional.
configuration.AddMapping(......);
configuration.BuildMappings();
ISessionFactory sessionFactory = configuration.BuildSessionFactory();
//ISessionFactory is setup so far. Now, configure logging.
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository(Assembly.GetEntryAssembly());
hierarchy.Root.RemoveAllAppenders();
FileAppender fileAppender = new FileAppender();
fileAppender.Name = "NHFileAppender";
fileAppender.File = logFilePath;
fileAppender.AppendToFile = true;
fileAppender.LockingModel = new FileAppender.MinimalLock();
fileAppender.Layout = new PatternLayout("%d{yyyy-MM-dd HH:mm:ss}:%m%n%n");
fileAppender.ActivateOptions();
Logger logger = hierarchy.GetLogger("NHibernate.SQL") as Logger;
logger.Additivity = false;
logger.Level = Level.Debug;
logger.AddAppender(fileAppender);
hierarchy.Configured = true;
You can further play with FileAppender and Logger as per your need. Please refer to this answer and this resource for more details. This explains the same with XML configuration; but the same should equally apply to code.