使用NHibernate3 Attributes的配置
在使用NHibernate3進(jìn)行數(shù)據(jù)庫操作時(shí),我們可以使用Attributes來配置實(shí)體類和映射關(guān)系,這樣可以更加直觀和簡(jiǎn)便。 所需的dll文件 在使用NHibernate3 Attributes
在使用NHibernate3進(jìn)行數(shù)據(jù)庫操作時(shí),我們可以使用Attributes來配置實(shí)體類和映射關(guān)系,這樣可以更加直觀和簡(jiǎn)便。
所需的dll文件
在使用NHibernate3 Attributes的配置之前,需要引用以下幾個(gè)dll文件:
- NHibernate.dll
配置
在開始配置實(shí)體類之前,我們需要先配置文件。該文件中包含了數(shù)據(jù)庫連接信息等相關(guān)配置。下面是一個(gè)示例配置:
lt;?xml version"1.0" encoding"utf-8"?gt;
lt;hibernate-configuration xmlns"urn:nhibernate-configuration-2.2"gt;
lt;session-factorygt;
lt;property name"">;/property>
lt;property name"_class">;/property>
lt;property name"_string">your_connection_stringlt;/property>
lt;property name"dialect">;/property>
lt;property name"show_sql">truelt;/property>
lt;/session-factorygt;
lt;/hibernate-configurationgt;
編寫并初始化代碼
接下來,我們需要編寫代碼來初始化NHibernate的配置和SessionFactory。以下是一個(gè)示例代碼:
static cfg new ();
static ISessionFactory sessions null;
//配置并打開Session
public static ISession OpenSession()
{
try
{
MemoryStream stream new MemoryStream();
true;
(stream, ());
stream.Position 0;
();
(stream);
();
sessions ().BuildSessionFactory();
}
catch (Exception e)
{
Console.WriteLine();
}
return ();
}
//關(guān)閉Session
public static void CloseSession()
{
if (sessions ! null !)
{
();
}
}
實(shí)體類attributes配置
在使用NHibernate3 Attributes的配置時(shí),我們需要為每個(gè)實(shí)體類添加一些attributes來指定映射關(guān)系和數(shù)據(jù)庫表結(jié)構(gòu)。以下是一個(gè)示例代碼:
// 用戶信息
[Serializable]
[Class(Table"UserInfo", Name"UserInfo")]
public class UserInfo
{
// 主鍵
[Id(Name "ID", Column "ID", TypeType typeof(Int64))]
[Key]
[Generator(Class "native")]
public virtual Int64 ID { get; set; }
// 用戶名
[Property]
public virtual String Username { get; set; }
// 密碼
[Property]
public virtual String Password { get; set; }
// 昵稱
[Property]
public virtual String Nikename { get; set; }
}
總結(jié)
通過使用NHibernate3 Attributes的配置,我們可以更加直觀和簡(jiǎn)便地定義實(shí)體類和映射關(guān)系。同時(shí),通過合理配置文件和編寫初始化代碼,我們可以輕松地使用NHibernate進(jìn)行數(shù)據(jù)庫操作。