Nhibernate3.3.3sp1基础搭建测试

实体类

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; }
    }
}
View Code

映射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>
View Code

实体调用测试

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();
        }
    }
}
View Code

配置文件(始终复制到目录)

<?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>
View Code

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:\develop\Codes\C#\SpringTest\Spring\NHibernateTest\hibernate.cfg.xml").BuildSessionFactory();
        }
        public ISession GetSession()
        {
            return _sessionFactory.OpenSession();
        }
    }
}
View Code

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)
View Code

 

posted on 2013-11-06 00:53 FlowingSun 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/FlowingSun/p/3409666.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值