nhibernate源碼分析之二:會話工廠
最後更新:2017-02-28
來源:互聯網
上載者:User
會話工廠是NHibernate中的關鍵類,它與資料庫連接、資料庫事務等進行互動,還儲存著與所有持久對象關聯的持久化對象,持久化類是持久化的關鍵,它實現基本的CRUD操作。
當使用者需要持久操作時,由會話工廠建立一個會話供使用者進行持久操作。
1. 會話工廠的建立
會話工廠由ISessionFactory介面實現,由Configuration的BuildSessionFactory方法建立,會話工廠應該使用Singleton模式。
如果要訪問多個資料庫,應建立多個會話工廠。
//*** Configuration.cs ***
public ISessionFactory BuildSessionFactory() {
// ...
Hashtable copy = new Hashtable();
foreach(DictionaryEntry de in properties) {
copy.Add(de.Key, de.Value);
}
return new SessionFactoryImpl(this, copy, interceptor);
}
其中SessionFactoryImpl為實現ISessionFactory的類,這個類的修飾為Internal。
2. 持久化類的建立
持久化類用於對持久對象進行持久化操作,每一個持久對象都有一個與之關聯的持久化對象。
持久化類繼承自IClassPersister介面,這個介面定義了用於持久對象的CRUD操作。
//*** SessionFactoryImpl ***
private IDictionary classPersisters;
持久化對象集合,Key為持久對象的類型;
private IDictionary classPersistersByName;
持久化對象集合,Key為持久對象的類名;
public SessionFactoryImpl(Configuration cfg, IDictionary properties, IInterceptor interceptor) {
// ...
foreach(PersistentClass model in cfg.ClassMappings) {
System.Type persisterClass = model.Persister;
IClassPersister cp;
//TODO: H2.0.3 created a PersisterFactory
if (persisterClass==null || persisterClass==typeof(EntityPersister)) {
cp = new EntityPersister(model, this);
} else if (persisterClass==typeof(NormalizedEntityPersister)) {
cp = new NormalizedEntityPersister(model, this);
} else {
cp = InstantiatePersister(persisterClass, model);
}
classPersisters[model.PersistentClazz] = cp;
classPersistersByName[model.Name] = cp ;
}
// ...
}
在建構函式中遍曆所有持久類映射資訊,然後根據持久類的持久類型建立一個持久化對象,並將此對象加入到集合中。
InstantiatePersister用於建立一個自訂的持久化對象,類名稱由對應檔中Class節點的Persister屬性指定,自訂持久化類必須實現IClassPersister介面.
3. 串連提供者
串連提供者由IConnectionProvider介面實現,會話工廠通過串連提供者與持久機制(資料庫等)進行互動,例如取得資料庫連接等。
//*** SessionFactoryImpl.cs ***
public SessionFactoryImpl(Configuration cfg, IDictionary properties, IInterceptor interceptor) {
// ...
connectionProvider = ConnectionProviderFactory.NewConnectionProvider(properties);
// ...
}
還是在建構函式中,串連提供者由串連提供者工廠根據配置屬性來建立。
//*** ConnectionProviderFactory ***
public static IConnectionProvider NewConnectionProvider(IDictionary settings) {
IConnectionProvider connections = null;
string providerClass = settings[Cfg.Environment.ConnectionProvider] as string;
if (providerClass != null) {
try {
connections = (IConnectionProvider) Activator.CreateInstance(System.Type.GetType(providerClass));
}
catch (Exception e) {
throw new HibernateException("Could not instantiate connection provider: " + providerClass);
}
}
else {
throw new NotImplementedException("We have not implemented user supplied connections yet.");
}
connections.Configure(settings);
return connections;
}
NewConnectionProvider方法通過配置中ConnectionProvider的值來建立串連提供者。目前的版本(v0.0.5)唯一可用的提供者只有DriverConnectionProvider類。
// 部分內容等有空再補充。