Windows · 2010-05-25

NHibernate查询、更新、删除

[TestFixture]

public class UserFixture { Configuration cfg; ISessionFactory factory ; readonly string userId=”test_user”;

//准备测试前的工作 [SetUp] public void SetUp() {

//Configuration对象能够解析所有.Net对象和后台数据库中的映射 关系。 cfg = new Configuration();

//Configuration对象会搜索装配件里的任何以hbm.xml 结尾的文件,前提是 //*.hbm.xml要编译为“嵌套的资源” cfg.AddAssembly(”NHibernate.Examples”); factory = cfg.BuildSessionFactory(); }

[TearDown]

public void TearDown() { //清除一些操作中生成的临时数据 }

///

///清除数据库中 Users表中的所有数据,提供一个干净的测试数据环境 /// [Test] public void ClearData() { //ISession对象提供一个到后台数据库的连接,参数由App.config指定 //ITransaction对象提供一个可以被NHibernate管理的事 务。 ISession session = factory.OpenSession(); ITransaction transaction = session.BeginTransaction();

//使用查询删除所有数据 session.Delete(”Select From User Where 1=1″);

transaction.Commit();

session.Close();

}

///

///测试往数据库中添加一个对象 /// [Test] public void AddTest() { ISession session = factory.OpenSession(); ITransaction transaction = session.BeginTransaction();

User newUser = new User(); newUser.Id = userId; newUser.UserName = “SkyDev”; newUser.Password = “abc123″; newUser.EmailAddress = skydev@pyp.edu.cn; newUser.LastLogon = DateTime.Now; session.Save(newUser);

transaction.Commit(); session.Close(); }

///

///更新数据库中的对象 /// [Test] public void UpdateTest() { ISession session = factory.OpenSession(); ITransaction transaction = session.BeginTransaction();

User aUser;

try {

//当userId指定的数据在数据库中不存在时会抛出异常 aUser= (User)session.Load(typeof(User), userId);

// set Joe Cool’s Last Login property aUser.LastLogon = DateTime.Now;

// flush the changes from the Session to the Database session.Flush();

transaction.Commit(); }               catch {  transaction.Rollback(); }

finally {  session.Close(); } }

///

///删除指定的对象 /// [Test] public void DeleteTest() { ISession session = factory.OpenSession(); ITransaction transaction = session.BeginTransaction();

User aUser;

try { //当userId指定的数据在数据库中不存在时会抛出异常 aUser = session.Load(typeof(User), userId) as User;

if (aUser!=null) { session.Delete(aUser); }

transaction.Commit(); }

catch { transaction.Rollback();  }

finally { session.Close();  }

}

}

}

正如你所看到的,关于NHiberante重要的事情是如此简单。继续并且查询你的数据库,验证一下User表里的新记录。 现在重要的事情就是你去操心业务对象并在进行处理的时候告诉NHibernate就可以了。

让我们来告诉你,当你有一个 UserID的时候如何获取对象(举 例说,登陆你的网站的时候)。仅仅一句话就可以打开Session,传入key就可以了

// open another session to retrieve the just inserted user session = factory.OpenSession(); User joeCool = (User)session.Load(typeof(User), “joe_cool”);

你所获取的User对象还在生存周期内!改变它的属性,并通过Flush()持久化到数据库。

// set Joe Cool’s Last Login property joeCool.LastLogon = DateTime.Now;

// flush the changes from the Session to the Database session.Flush();

你所要做的就是通过NHibernate来进行你需要的改变,并调用Session的Flush()方法提 交。验证一下数据库,查查用户ID为”joe_cool”的记录中”LastLogon”的更改。

还有更好的,你可以以System.Collections.IList的方式来获取从表中的对象。如下 IList userList = session.CreateCriteria(typeof(User)).List(); foreach(User user in userList) { System.Diagnostics.Debug.WriteLine(user.Id + ” last logged in at ” + user.LastLogon); }

这个查询将会返回所有表记录。往往你需要做更多的控制,比如说获取从 March 14, 2004 10:00 PM 以后登陆的用户,如下:

IList recentUsers = session.CreateCriteria(typeof(User)) .Add(Expression.Expression.Gt(”LastLogon”, new DateTime(2004, 03, 14, 20, 0, 0))) .List();

foreach(User user in recentUsers) { System.Diagnostics.Debug.WriteLine(user.Id + ” last logged in at ” + user.LastLogon); }

文档里还有一堆健壮的查询方式让你调用,这里仅仅让你对NHibernate 所提供的强有力的工具有一定的了解。

最后调用Session对象的Close()方法,释放NHibernate所使用的ADO.Net连接资源 // tell NHibernate to close this Session session.Close();