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();
}