NHibernate执行SQL语句
如果需要在使用NHibernate作为数据访问层的时候执行SQL语句,可以参考以下方法:
1
using System.Web;2
using NHibernate;3
using NHibernate.Cfg;4
using NHibernate.Engine;5

6
namespace NHibernateStudy.DAL7


{ 8
public sealed class SessionManager9

{10
private const string CurrentSessionKey = "nhibernate.current_session";11
private static readonly ISessionFactory sessionFactory;12

13
static SessionManager()14

{ 15
//Configuration cf = new Configuration();16
//cf.AddAssembly("Example.Model");17
//sessionFactory = cf.Configure().BuildSessionFactory();18
sessionFactory = new Configuration().Configure().BuildSessionFactory();19
}20

21
public static ISession GetCurrentSession()22

{23
HttpContext context = HttpContext.Current;24
ISession currentSession = context.Items[CurrentSessionKey] as ISession;25

26
if (currentSession == null)27

{28
currentSession = sessionFactory.OpenSession();29
context.Items[CurrentSessionKey] = currentSession;30
}31

32
return currentSession;33
}34

35
public static void CloseSession()36

{37
HttpContext context = HttpContext.Current;38
ISession currentSession = context.Items[CurrentSessionKey] as ISession;39

40
if (currentSession == null)41

{42
// No current session43
return;44
}45

46
currentSession.Close();47
context.Items.Remove(CurrentSessionKey);48
}49

50
public static void CloseSessionFactory()51

{52
if (sessionFactory != null)53

{54
sessionFactory.Close();55
}56
}57

58
public static ISessionFactoryImplementor GetISessionFactoryImplementor()59

{60
if (sessionFactory != null)61

{62
return (ISessionFactoryImplementor)sessionFactory;63
}64
else65

{66
return null;67
}68
}69
}70

71
}72

客户端调用:
protected void Test
{
ISessionFactoryImplementor sfi = SessionManager.GetISessionFactoryImplementor();
IDbConnection conn = sfi.OpenConnection();
IDbTransaction tran = conn.BeginTransaction();
try
{
IDbCommand com = conn.CreateCommand();
//以下可以随意调用ADO.NET了
tran.Commit();
}
catch
{
tran.Rollback();
}
}
浙公网安备 33010602011771号