using System; using System.Collections.Generic; using System.Text; using NHibernate; using NHibernate.Cfg; using NHibernate.Tool.hbm2ddl; namespace NhibernateSample1 { publicclass UserFixure { private ISession session; public UserFixure() {
} /**//// <summary> /// 创建表 /// </summary> publicbool ExportTable() { try { Configuration cfg = new Configuration().Configure(@"E:/my project/nhibernate study/simle 1/NHibernateStudy1/NhibernateSample1/hibernate.cfg.xml"); session = NHibernateHelper.GetCurrentSession(); ITransaction transaction = session.BeginTransaction(); new SchemaExport(cfg).Create(true, true); transaction.Commit(); returntrue; } catch(Exception ex) { throw ex; } finally { session.Close(); } } /**//// <summary> /// 添加 /// </summary> publicint Add() { try { User u = new User(); u.Name = Guid.NewGuid().ToString(); u.Pwd = "124"; session = NHibernateHelper.GetCurrentSession(); ITransaction transaction = session.BeginTransaction(); session.Save(u); transaction.Commit(); return u.Id; } catch (Exception ex) { throw ex; } finally { session.Close(); } } /**//// <summary> /// 更新 /// </summary> /// <param name="uid"></param> publicbool Update(int uid) { try { session = NHibernateHelper.GetCurrentSession(); ITransaction transaction = session.BeginTransaction(); User u = session.Load(typeof(User), uid) as User; if (u != null) { u.Name = "updatedName"; session.SaveOrUpdate(u); transaction.Commit(); u = session.Load(typeof(User), uid) as User; if (u.Name == "updatedName") { returntrue; } } returnfalse; } catch (Exception ex) { throw ex; } finally { session.Close(); } } /**//// <summary> /// 删除 /// </summary> /// <param name="uid"></param> /// <returns></returns> publicbool Delete(int uid) { try { session = NHibernateHelper.GetCurrentSession(); ITransaction transaction = session.BeginTransaction(); User u = session.Get(typeof(User), uid) as User; if (u != null) { session.Delete(u); transaction.Commit(); u = session.Get(typeof(User), uid) as User; if (u == null) { returntrue; } } returnfalse; } catch (Exception ex) { throw ex; } finally { session.Close(); } } public System.Collections.IList Query() { try { session = NHibernateHelper.GetCurrentSession(); ITransaction transaction = session.BeginTransaction(); System.Collections.IList list= session.CreateQuery("select u from User as u").List(); transaction.Commit(); return list; } catch (Exception ex) { throw ex; } finally { session.Close(); } } } }
1. 学习目的学习Nhibernate基础知识。掌握Nhibernate的配置方法,实现对单表的简单操作,如:创建表,查询,添加,删除,修改。2. 开发环境+前期准备开发环境: windows 2003,Visual studio .Net 2005,Sql server 2005 developer edition前期准备: Nhibernate框架,我用的目前最新版NHibernate-