[Hibernate]在VS2010中应用NHibernate 3.2与MySQL

在VS2010中应用NHibernate 3.2与MySQL

罗朝辉 (http://kesalin.cnblogs.com/)

本文遵循“署名-非商业用途-保持一致”创作公用协议
 
本文讲述了在VS2010中使用NHibernate 3.2与MySQL的一个简单示例。
 
工具下载:
1,NHibernate 3.2
官网下载:NHibernate,下载完之后,将之解压到某个目录,比如:C:\Share\Libraries\NHibernate-3.2.0.GA。
 
2,创建数据库
本文使用前文《在VS2010中应用Entity framework与MySQL》中创建的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 version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="NHSample" assembly="NHSample">
<class name="Customer" table="Customer">
<id name="ID" column="id">
<generator class="assigned"/>
</id>
<property name="Address" column="Address" type="String" length="255" />
<property name="Name" column="Name" type="String" length="255" />
</class>
</hibernate-mapping>
该xml定义概念模型与数据库之间的映射关系。该xml的命名严格遵守如下格式:类名 + .hbm + .xml。
 
5,下面我们来对数据源进行配置,向工程中新建一个名为 app.config 的xml数据文件,其内容如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">
NHibernate.Connection.DriverConnectionProvider
</property>
<property name="dialect">NHibernate.Dialect.MySQL5Dialect</property>
<property name="query.substitutions">hqlFunction=SQLFUNC</property>
<property name="connection.driver_class">
NHibernate.Driver.MySqlDataDriver
</property>
<property name="connection.connection_string">
Database=EFSample;Data Source=localhost;User Id=XXX;Password=XXX
</property>
<property name="show_sql">false</property>
<mapping assembly="NHSample" />
</session-factory>
</hibernate-configuration>
</configuration>
在上面的 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();
}
}
}
 
 
 
 
posted @ 2012-03-11 16:51  飘飘白云  阅读(2215)  评论(0编辑  收藏  举报
本博客遵循 Creative Commons License “署名-非商业用途-保持一致”创作共用协议。 与我联系