4. 使用NHibernate的API進行程式設計
資料庫程式設計不外乎“新增”、“刪除”、“更新”,看看NHibernate是如何實現這三種操作吧。
(1) 在類中宣告NHibernate的Factory
private static Configuration mCfg=new Configuration();
private static NHibernate.ISessionFactory SessionFactory=null;
(2) 在系統初始化的時候載入XML,並建立Factory
mCfg.AddXmlFile( ApplicationPath +"/Course.hbm.xml");
mCfg.AddXmlFile( ApplicationPath +"/Student.hbm.xml");
SessionFactory=mCfg.BuildSessionFactory();
(3) 使用HSql查詢
string hsql="from Student where StudentName='kexd'";
ISession vSession= SessionFactory.OpenSession();
IQuery query = vSession.CreateQuery(hsql);
IList list = query.List();
if(list.Count>0){
Student obj=(Student)list[0];
//.....
}
vSession.Close();
(4) 根據主鍵查詢
int studentID=1;
ISession vSession= SessionFactory.OpenSession();
Student obj=(Student) vSession.Load(typeof(Student),studentID);
vSession.Close();
(5) 插入
Student obj=new Student();
obj.StudentName="wuyang";
obj.StudentPassword="helloWorld";
ITransaction vTransaction = vSession.BeginTransaction();
try
{
vSession.Save(obj);
vTransaction.Commit();
}
catch(Exception)
{
vTransaction.Rollback();
}
vSession.Close();
(6) 更新
ISession vSession= Config.SessionFactory.OpenSession();
IQuery query = vSession.CreateQuery("from Student where StudentName='kexd'");
IList list = query.List();
ITransaction vTransaction = vSession.BeginTransaction();
try
{
foreach(Student obj in list)
{
obj.EmailAddress="kesfzu@21cn.com";
vSession.Save(obj);
}
vTransaction.Commit();
}
catch(Exception)
{
vTransaction.Rollback();
}
finally
{
vSession.Close();
}
(7) 刪除
ISession vSession= Config.SessionFactory.OpenSession();
IQuery query = vSession.CreateQuery("from Student where StudentName='kexd'");
IList list = query.List();
ITransaction vTransaction = vSession.BeginTransaction();
try
{
foreach(Student obj in list)
{
vSession.Delete(obj);
}
vTransaction.Commit();
}
catch(Exception)
{
vTransaction.Rollback();
}
finally
{
vSession.Close();
}