在VS2010中应用NHibernate 3.2与MySQL
罗朝辉 ()
本文遵循“”创作公用协议
本文讲述了在VS2010中使用NHibernate 3.2与MySQL的一个简单示例。
工具下载:
1,NHibernate 3.2
官网下载: ,下载完之后,将之解压到某个目录,比如:C:\Share\Libraries\NHibernate-3.2.0.GA。
2,创建数据库
本文使用前文《 》中创建的MySql数据库表 customer,请参考 步骤3,在这里就不再多啰嗦了。
3,新建C#控制台程序 NHSample,然后在工程中新增类Customer,其内容如下:
// Author:罗朝辉 // http://kesalin.cnblogs.com/ namespace NHSample { class Customer { public virtual int ID { get; set; } public virtual string Address { get; set; } public virtual string Name { get; set; } override public string ToString() { return string.Format("Customer Name: {0}, Address: {1}", this.Name, this.Address); } } }
该类就是将与数据库进行映射的概念模型类。
4,再向工程中新建一个名为Customer.hbm.xml的xml数据文件,其内容如下:
该xml定义概念模型与数据库之间的映射关系。该xml的命名严格遵守如下格式:类名 + .hbm + .xml。
5,下面我们来对数据源进行配置,向工程中新建一个名为 app.config 的xml数据文件,其内容如下:
NHibernate.Connection.DriverConnectionProvider NHibernate.Dialect.MySQL5Dialect hqlFunction=SQLFUNC NHibernate.Driver.MySqlDataDriver Database=EFSample;Data Source=localhost;User Id=XXX;Password=XXX false
在上面的 xml 中,我们配置了MySql数据源,并在程序中不打算输出sql语句信息(就是关闭log),注意其中的User Id 和 Password分别是你数据库的用户名和密码。
6,测试
首先导入NHibernate 库,右击 References 选择 Add Reference,选择 Browser之前解压的目录C:\NHibernate-3.2.0.GA\Required_Bins\,导入Iesi.Collections.dll 和NHibernate.dll两个库。
下面来编写测试代码,代码大体与前文一致。
// Author:罗朝辉 // http://kesalin.cnblogs.com/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Collections; using System.Diagnostics; using NHibernate; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Mapping.ByCode; namespace NHSample { class Program { const int MaxRow = 1000; static ISessionFactory sessionFactory = null; public static void InitSessionFactory() { if (sessionFactory == null) { Configuration config = new Configuration(); config.AddClass(typeof(NHSample.Customer)); sessionFactory = config.BuildSessionFactory(); if (sessionFactory == null) { Console.WriteLine(" >> Error: Failed to build session factory!"); } } } public static ISession OpenSession() { if (sessionFactory == null) { InitSessionFactory(); } if (sessionFactory == null) { return null; } ISession session = sessionFactory.OpenSession(); if (session == null) { Console.WriteLine(" >> Error: Failed to open session!"); } return session; } public static void DeleteData() { ISession session = OpenSession(); if (session != null) { ICriteria crit = session.CreateCriteria(typeof(Customer)); IList result = crit.List(); foreach (Customer item in result) { session.Delete(item); } session.Flush(); session.Close(); } } public static void InsertData(Customer[] cs) { ISession session = OpenSession(); if (session != null) { foreach (Customer c in cs) { session.Save(c); } session.Flush(); session.Close(); } } public static void QueryData() { ISession session = OpenSession(); if (session != null) { for (int i = 1; i <= MaxRow; i++) { String address = i.ToString(); IList results = session.CreateQuery("from Customer as t where t.Address = :value").SetString("value", address).List(); if (results.Count > 0) { Customer c = (Customer)(results[0]); Console.WriteLine(c); } } session.Close(); } } protected static object LoadObjectByProperty(ISession session, string typeName, string propertyName, string propertyValue) { IList results = session.CreateQuery("from " + typeName + " as t where t." + propertyName + " = :value").SetString("value", propertyValue).List(); if (results.Count > 0) return (results[0]); else return null; } protected static Customer LoadCustomerByName(ISession session, string name) { return (LoadObjectByProperty(session, "Customer", "Name", name) as Customer); } protected static Customer LoadCustomerByAddress(ISession session, string address) { return (LoadObjectByProperty(session, "Customer", "Address", address) as Customer); } static void Main(string[] args) { Customer[] cs = new Customer[MaxRow]; for (int i = 1; i <= MaxRow; i++) { StringBuilder sb = new StringBuilder(); sb.Append("用户"); sb.Append(i); Customer c = new Customer(); c.ID = i; c.Name = sb.ToString(); c.Address = i.ToString(); cs[i - 1] = c; } Console.WriteLine("=================== TEST START ==================="); DeleteData(); Console.WriteLine(">> Storage test start..."); Stopwatch sw = Stopwatch.StartNew(); InsertData(cs); sw.Stop(); Console.WriteLine("<< Store data seconds: " + sw.ElapsedMilliseconds / 1000 + " ( " + sw.ElapsedMilliseconds + " miliseconds)"); Console.WriteLine(">> Query test start..."); sw = Stopwatch.StartNew(); QueryData(); sw.Stop(); Console.WriteLine("<< Query data seconds: " + sw.ElapsedMilliseconds / 1000 + " ( " + sw.ElapsedMilliseconds + " miliseconds)"); Console.WriteLine(">> Delete test start..."); sw = Stopwatch.StartNew(); DeleteData(); sw.Stop(); Console.WriteLine("<< Delete data seconds: " + sw.ElapsedMilliseconds / 1000 + " ( " + sw.ElapsedMilliseconds + " miliseconds)"); Console.ReadLine(); } } }