实体类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NHibernateTest.Entity { public class Customer { public virtual int CustomerID { get; set; } public virtual string Version { get; set; } public virtual string FirstName { get; set; } public virtual string LastName { get; set; } } }
映射XML(嵌入的资源)
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernateTest" namespace="NHibernateTest.Entity"> <class name=" NHibernateTest.Entity.Customer,NHibernateTest" table="Customer" lazy="false"> <id name="CustomerID" column="CustomerID" type="int"> <generator class="native" /> </id> <property name="Version" column="Version" type="String" length="50"/> <property name="FirstName" column="FirstName" type="String" length="50"/> <property name="LastName" column="LastName" type="String" length="50" /> </class> </hibernate-mapping>
实体调用测试
using System; using System.Collections; using NHibernate; using NHibernate.Cfg; //using NHibernate.Expression;//nh低版本才有该引用,nh2.1以上则引用using NHibernate.Criterion; using NHibernateTest.Entity; using NHibernate.Criterion; namespace NHibernateTest { /// <summary> /// CustomerFixture 的摘要说明。 /// </summary> public class CustomerFixture { public CustomerFixture() { // // TODO: 在此处添加构造函数逻辑 // } public void ValidateQuickStart() { try { //得到NHibernate的配置 //MyConfiguration config = new MyConfiguration(); //Configuration cfg = config.GetConfig(); NHibernateHelper nhh = new NHibernateHelper(); //ISessionFactory factory = cfg.BuildSessionFactory(); //ISession session = factory.OpenSession(); ISession session = nhh.GetSession(); ITransaction transaction = session.BeginTransaction(); //ISessionFactory factory = Configuration.BuildSessionFactory(); Customer newCustomer = null; try { newCustomer = (Customer)session.Load(typeof(Customer), 2); } catch { } if (newCustomer == null) { newCustomer = new Customer(); newCustomer.FirstName = "Joseph Cool"; newCustomer.LastName = "joe@cool.com"; newCustomer.Version = DateTime.Now.ToString(); // Tell NHibernate that this object should be saved session.Save(newCustomer); } // commit all of the changes to the DB and close the ISession transaction.Commit(); session.Close(); ///首先,我们要从ISessionFactory中获取一个ISession(NHibernate的工作单元)。 ///ISessionFactory可以创建并打开新的Session。 ///一个Session代表一个单线程的单元操作。 ///ISessionFactory是线程安全的,很多线程可以同时访问它。 ///ISession不是线程安全的,它代表与数据库之间的一次操作。 ///ISession通过ISessionFactory打开,在所有的工作完成后,需要关闭。 ///ISessionFactory通常是个线程安全的全局对象,只需要被实例化一次。 ///我们可以使用GoF23中的单例(Singleton)模式在程序中创建ISessionFactory。 ///这个实例我编写了一个辅助类NHibernateHelper 用于创建ISessionFactory并配置ISessionFactory和打开 ///一个新的Session单线程的方法,之后在每个数据操作类可以使用这个辅助类创建ISession 。 // open another session to retrieve the just inserted Customer //session = factory.OpenSession(); session = nhh.GetSession(); Customer joeCool = (Customer)session.Load(typeof(Customer), 2); // set Joe Cool's Last Login property joeCool.Version = DateTime.Now.ToString(); // flush the changes from the Session to the Database session.Flush(); IList recentCustomers = session.CreateCriteria(typeof(Customer)) .Add(Expression.Gt("Version", new DateTime(2004, 03, 14, 20, 0, 0).ToString())) .List(); foreach (Customer Customer in recentCustomers) { //Assert.IsTrue(Customer.LastLogon > (new DateTime(2004, 03, 14, 20, 0, 0)) ); Console.WriteLine(Customer.FirstName); Console.WriteLine(Customer.LastName); } session.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } Console.ReadLine(); } } }
配置文件(始终复制到目录)
<?xml version="1.0" encoding="utf-8"?> <!-- This template was written to work with NHibernate.Test. Copy the template to your NHibernate.Test project folder and rename it in hibernate.cfg.xml and change it for your own use before compile tests in VisualStudio. --> <!-- This is the System.Data.dll provider for SQL Server --> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" > <session-factory name="NHibernateTest"> <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property> <property name="connection.connection_string"> Server=(local);initial catalog=NHTest;Integrated Security=SSPI </property> <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property> <mapping assembly="NHibernateTest"/> </session-factory> </hibernate-configuration>
Session工厂
using NHibernate; using NHibernate.Cfg; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NHibernateTest { public class NHibernateHelper { private ISessionFactory _sessionFactory; public NHibernateHelper() { _sessionFactory = GetSessionFactory(); } private ISessionFactory GetSessionFactory() { return (new Configuration()).Configure().BuildSessionFactory(); //return (new Configuration()).Configure("D:developCodesC#SpringTestSpringNHibernateTesthibernate.cfg.xml").BuildSessionFactory(); } public ISession GetSession() { return _sessionFactory.OpenSession(); } } }
sql(需建NHTest库)
create Table Customer ( CustomerID int primary key identity(1,1) not null, [Version] varchar(50) not null, FirstName varchar(50) not null, LastName varchar(50) not null ) create Table [Order] ( OrderID int primary key identity(1,1) not null, [Version] varchar(50) not null, OrderDate date not null, CustomerID int not null foreign key references [Customer](CustomerID) ) create Table Product ( ProductID int Primary key identity(1,1) not null, [Version] varchar(50), Name varchar(50), Cost varchar(50) ) create Table OrderProduct ( OrderID int not null foreign key references [Order](OrderID), ProductID int not null foreign key references [Product](ProductID) ) insert into Customer([Version],FirstName,LastName) values('1.0', 'sam', 'sir') insert into [Order]([Version],OrderDate,CustomerID) values('1.0',GETDATE(),2) insert into Product([Version],Name,Cost) values('1.0','黑莓','$30') insert into OrderProduct values(2,3)