C#.NET编程----Spring.NET & NHibernate整合(二)
任何熟悉Hibernate的人会发现这篇指南和Glen Smith 的 A Hitchhiker's Guide to Hibernate 非常相近。这里的内容正是基于他的指南,因此所有的感谢都应该给与他。
NHibernate的文档并非每处都和Hibernate的文档一致。然而,项目的相似应该能使读者通过读Hibernate的文档来很好的理解NHibernate如何工作。
这篇文档意在让你尽可能快的开始使用NHibernate。它将介绍如何持久化一个简单的对象到一张表里。想得到更多的复杂的例子,可以参考NUnit测试及附带代码。
我们将进行以下步骤。
1.新建一个将要持久化.Net对象的表
2.构建一个可以让NHibernate知道如何持久化对象属性的映射文件
3.构建一个需要被持久化的.Net类
4.构建一个存放NHibernater的配置文件的对像
新建项目
项目名称为:NHibernateSample,名字空间:OKEC.Sample.NHibernate
建立数据表
数据库为SQLServer2000,表名为:my_users
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[my_users]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[my_users]
GO
CREATE TABLE [dbo].[my_users] (
[LogonId] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[UserName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[Password] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[EmailAddress] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[LastLogon] [datetime] NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[my_users] ADD
CONSTRAINT [PK_my_users] PRIMARY KEY CLUSTERED
(
[LogonId]
) ON [PRIMARY]
GO
drop table [dbo].[my_users]
GO
CREATE TABLE [dbo].[my_users] (
[LogonId] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[UserName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[Password] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[EmailAddress] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[LastLogon] [datetime] NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[my_users] ADD
CONSTRAINT [PK_my_users] PRIMARY KEY CLUSTERED
(
[LogonId]
) ON [PRIMARY]
GO
建立XML对像映射文件
现在我们有数据表和需要去映射它的.Net类。我们需要一种方式去让NHibernate知道如何从一个映射到另一个。这个任务依赖于映射文件来完成。最易于管理的办法是为每一个类写一个映射文件,如果你命名它是User.hbm.xml并且把它放在和类的同一个目录里,NHiberante将会使得事情简单起来。下面是User.hbm.xml的例子:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
<class name=" OKEC.Sample.NHibernate.NHibernateTest.User,NHibernateSample" table="my_users">
<id name="Id" column="LogonId" type="String" length="20">
<generator class="assigned" />
</id>
<property name="UserName" column="UserName" type="String" length="40"/>
<property name="Password" column="Password" type="String" length="20"/>
<property name="EmailAddress" column="EmailAddress" type="String" length="40"/>
<property name="LastLogon" column="LastLogon" type="DateTime"/>
</class>
</hibernate-mapping>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
<class name=" OKEC.Sample.NHibernate.NHibernateTest.User,NHibernateSample" table="my_users">
<id name="Id" column="LogonId" type="String" length="20">
<generator class="assigned" />
</id>
<property name="UserName" column="UserName" type="String" length="40"/>
<property name="Password" column="Password" type="String" length="20"/>
<property name="EmailAddress" column="EmailAddress" type="String" length="40"/>
<property name="LastLogon" column="LastLogon" type="DateTime"/>
</class>
</hibernate-mapping>
注意事项:在Visual Studio 2003/2005中要将此文件的属性设置为“嵌入的资源”(Embedded Resource)
建立对像
对像定义:User.cs
using System;
namespace OKEC.Sample.NHibernate.NHibernateTest
{
/// <summary>
/// Summary description for User.
/// </summary>
public class User
{
private string id;
private string userName;
private string password;
private string emailAddress;
private DateTime lastLogon;
public User()
{
}
public string Id
{
get { return id; }
set { id = value; }
}
public string UserName
{
get { return userName; }
set { userName = value; }
}
public string Password
{
get { return password; }
set { password = value; }
}
public string EmailAddress
{
get { return emailAddress; }
set { emailAddress = value; }
}
public DateTime LastLogon
{
get { return lastLogon; }
set { lastLogon = value; }
}
}
}
namespace OKEC.Sample.NHibernate.NHibernateTest
{
/// <summary>
/// Summary description for User.
/// </summary>
public class User
{
private string id;
private string userName;
private string password;
private string emailAddress;
private DateTime lastLogon;
public User()
{
}
public string Id
{
get { return id; }
set { id = value; }
}
public string UserName
{
get { return userName; }
set { userName = value; }
}
public string Password
{
get { return password; }
set { password = value; }
}
public string EmailAddress
{
get { return emailAddress; }
set { emailAddress = value; }
}
public DateTime LastLogon
{
get { return lastLogon; }
set { lastLogon = value; }
}
}
}
编写Nhibernate的初始化配置程序
程序名:MyConfiguration.cs
using System;
using NHibernate.Cfg;
namespace OKEC.Sample.NHibernate.NHibernateTest
{
/// <summary>
/// MyConfiguration 的摘要说明。
/// </summary>
public class MyConfiguration
{
public MyConfiguration()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public Configuration GetConfig()
{
try
{
Configuration cfg = new Configuration(); cfg.SetProperty("hibernate.connection.provider","NHibernate.Connection.DriverConnectionProvider");
//请修改此行中的SQLServer的配置
cfg.SetProperty("hibernate.connection.connection_string","Data Source=192.168.88.15;Database=liluhua;User ID=sa;Password=sa;Trusted_Connection=False");
cfg.SetProperty("hibernate.dialect","NHibernate.Dialect.MsSql2000Dialect");
cfg.SetProperty("hibernate.connection.driver_class","NHibernate.Driver.SqlClientDriver");
cfg.AddAssembly("NHibernateSample");
return cfg;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
return null;
}
}
}
using NHibernate.Cfg;
namespace OKEC.Sample.NHibernate.NHibernateTest
{
/// <summary>
/// MyConfiguration 的摘要说明。
/// </summary>
public class MyConfiguration
{
public MyConfiguration()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public Configuration GetConfig()
{
try
{
Configuration cfg = new Configuration(); cfg.SetProperty("hibernate.connection.provider","NHibernate.Connection.DriverConnectionProvider");
//请修改此行中的SQLServer的配置
cfg.SetProperty("hibernate.connection.connection_string","Data Source=192.168.88.15;Database=liluhua;User ID=sa;Password=sa;Trusted_Connection=False");
cfg.SetProperty("hibernate.dialect","NHibernate.Dialect.MsSql2000Dialect");
cfg.SetProperty("hibernate.connection.driver_class","NHibernate.Driver.SqlClientDriver");
cfg.AddAssembly("NHibernateSample");
return cfg;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
return null;
}
}
}
编写调用程序
准备好上面的一切,我们就可以开始编辑启动程序,来测试你的第一个Nhibernate程序了。
程序名:UserFixture.cs
using System;
using System.Collections;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Expression;
namespace OKEC.Sample.NHibernate.NHibernateTest
{
/// <summary>
/// UserFixture 的摘要说明。
/// </summary>
public class UserFixture
{
public UserFixture()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public void ValidateQuickStart()
{
try
{
//得到NHibernate的配置
MyConfiguration config = new MyConfiguration();
Configuration cfg = config.GetConfig();
ISessionFactory factory = cfg.BuildSessionFactory();
ISession session = factory.OpenSession();
ITransaction transaction = session.BeginTransaction();
User newUser = null;
try
{
newUser = (User)session.Load(typeof(User), "joe_cool");
}
catch
{
}
if(newUser==null)
{
newUser = new User();
newUser.Id = "joe_cool";
newUser.UserName = "Joseph Cool";
newUser.Password = "abc123";
newUser.EmailAddress = "joe@cool.com";
newUser.LastLogon = DateTime.Now;
// Tell NHibernate that this object should be saved
session.Save(newUser);
}
// commit all of the changes to the DB and close the ISession
transaction.Commit();
session.Close();
// open another session to retrieve the just inserted user
session = factory.OpenSession();
User joeCool = (User)session.Load(typeof(User), "joe_cool");
// set Joe Cool's Last Login property
joeCool.LastLogon = DateTime.Now;
// flush the changes from the Session to the Database
session.Flush();
IList recentUsers = session.CreateCriteria(typeof(User))
.Add(Expression.Gt("LastLogon", new DateTime(2004, 03, 14, 20, 0, 0)))
.List();
foreach(User user in recentUsers)
{
//Assert.IsTrue(user.LastLogon > (new DateTime(2004, 03, 14, 20, 0, 0)) );
Console.WriteLine(user.UserName);
Console.WriteLine(user.Password);
}
session.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
Console.ReadLine();
}
}
}
using System.Collections;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Expression;
namespace OKEC.Sample.NHibernate.NHibernateTest
{
/// <summary>
/// UserFixture 的摘要说明。
/// </summary>
public class UserFixture
{
public UserFixture()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public void ValidateQuickStart()
{
try
{
//得到NHibernate的配置
MyConfiguration config = new MyConfiguration();
Configuration cfg = config.GetConfig();
ISessionFactory factory = cfg.BuildSessionFactory();
ISession session = factory.OpenSession();
ITransaction transaction = session.BeginTransaction();
User newUser = null;
try
{
newUser = (User)session.Load(typeof(User), "joe_cool");
}
catch
{
}
if(newUser==null)
{
newUser = new User();
newUser.Id = "joe_cool";
newUser.UserName = "Joseph Cool";
newUser.Password = "abc123";
newUser.EmailAddress = "joe@cool.com";
newUser.LastLogon = DateTime.Now;
// Tell NHibernate that this object should be saved
session.Save(newUser);
}
// commit all of the changes to the DB and close the ISession
transaction.Commit();
session.Close();
// open another session to retrieve the just inserted user
session = factory.OpenSession();
User joeCool = (User)session.Load(typeof(User), "joe_cool");
// set Joe Cool's Last Login property
joeCool.LastLogon = DateTime.Now;
// flush the changes from the Session to the Database
session.Flush();
IList recentUsers = session.CreateCriteria(typeof(User))
.Add(Expression.Gt("LastLogon", new DateTime(2004, 03, 14, 20, 0, 0)))
.List();
foreach(User user in recentUsers)
{
//Assert.IsTrue(user.LastLogon > (new DateTime(2004, 03, 14, 20, 0, 0)) );
Console.WriteLine(user.UserName);
Console.WriteLine(user.Password);
}
session.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
Console.ReadLine();
}
}
}
测试你的程序
如果运行后没有出错,显示了结果,说明你的第一个NHibernate程序成功了。
如果会如下:
Joseph Cool
abc123
abc123
文档中的项目源代码请从以下地址下载:
http://www.springframework.cn/read.php?fid=8&tid=2&toread=1
完整的文档请下载PDF文档:
http://www.springframework.cn/read.php?fid=2&tid=1&toread=1