標籤:
配置NHibernate串連sqlite資料庫檔案,以HSqlite.cfg為例:
<?xml version="1.0" encoding="utf-8"?><hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" > <session-factory name="NHibernate.Test"> <property name="current_session_context_class">thread_static</property> <property name="connection.driver_class">NHibernate.Driver.SQLite20Driver</property> <property name="connection.connection_string"></property> <property name="adonet.batch_size">10</property> <property name="show_sql">true</property> <property name="dialect">NHibernate.Dialect.SQLiteDialect</property> <property name="use_outer_join">true</property> <property name="command_timeout">60</property> <property name="hbm2ddl.auto">update</property> <property name="query.substitutions">true=1;false=0</property> <property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property> <mapping assembly="InspectClient.Domain"/> </session-factory></hibernate-configuration>
其中current_session_context_class主要用於配置session類型,winform類型使用thread_static參數,web類型使用web參數。
sessionhelper
public static class SessionBuilder { private static readonly ISessionFactory _sessionFactory ; private static readonly object _lock = new object(); static SessionBuilder() { lock (_lock) { _sessionFactory = new Configuration().Configure("HSqlite.cfg.xml") .SetProperty("connection.connection_string", SqliteConfig.DataSource) .BuildSessionFactory(); } } #region Session在當前內容相關的操作 private static void BindContext() { lock (_lock) { if (!CurrentSessionContext.HasBind(_sessionFactory)) { CurrentSessionContext.Bind(_sessionFactory.OpenSession()); } } } private static void UnBindContext() { lock (_lock) { if (CurrentSessionContext.HasBind(_sessionFactory)) { CurrentSessionContext.Unbind(_sessionFactory); } } } public static void CloseCurrentSession() { UnBindContext(); } public static ISession GetCurrentSession() { BindContext(); return _sessionFactory.GetCurrentSession(); } #endregion #region 關閉SessionFactory(一般在應用程式結束時操作) public static void CloseSessionFactory() { if (!_sessionFactory.IsClosed) { _sessionFactory.Close(); } } #endregion #region 開啟一個新的Session public static ISession OpenSession() { lock (_lock) { return _sessionFactory.OpenSession(); } } #endregion }
使用NHibernate 2.1適配Sqlite資料庫