Nhibernate入门


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
下载:nhibernate

使用方式:
1,项目引入dll:

    * Antlr3.Runtime.dll
    * Castle.Core.dll
    * Iesi.Collections.dll
    * LinFu.DynamicProxy.dll
    * log4net.dll
    * NHibernate.ByteCode.Castle.dll
    * NHibernate.ByteCode.LinFu.dll
    * NHibernate.dll
    * nunit.core.dll
    * nunit.framework.dll

2,编写数据库连接:对于一般的应用程序,编写hibernate.cfg.xml放在根目录下,属性设置为始终复制,因为nhibernate是对输出目录bin的文件进行读取的,对于web可在web.config中进行添加。
      1)hibernate.cfg.xml,在官方文档的Configuration_Templates文件夹下有模板,例子如下:
       



  
    NHibernate.Driver.SqlClientDriver
    
      Server=(local);initial catalog=nhibernate;Integrated Security=SSPI;user id=sa;password=123abc;min pool size=1;max pool size=512
    
    10
    false
    NHibernate.Dialect.MsSql2000Dialect
    true
    60
    true 1, false 0, yes 'Y', no 'N'
    NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu
  

 
     2) web.config 在下进行Nhibernate 配置

            
3,编写实体类 4,编写实体类映射文件 如:Product.hbm.xml,将此其属性设置为嵌入资源,这是因为NHibernate是通过查找程序集中的资源文件来进行实体的映射,故要将映射文件嵌入到程序集中。 如: 注:1), 要为Microsoft Visual Studio 2008添加编写NHibernate配置文件智能提示的功能。只要在下载的NHibernate里找到configuration.xsd和 nhibernate-mapping.xsd两个文件并复制到X:\Program Files\Microsoft Visual Studio 9.0\Xml\Schemas目录即可。 2),此时即可通过架构类来自动生成数据库表 var cfg = new Configuration(); cfg.Configure(); cfg.AddAssembly(typeof(Product).Assembly); new SchemaExport(cfg).Execute(true, true, false); 5,因为操作数据库是用Session来完成的,可编写一helper类,用来集中处理, 编写NHibernateHelper.cs如下: using NHibernate; using NHibernate.Cfg; using NHebernateTest.Domain; namespace NHebernateTest.Repositories { public class NHibernateHelper { private static ISessionFactory _sessionFactory; private static ISessionFactory SessionFactory { get { if (_sessionFactory == null) { var configuration = new Configuration(); configuration.Configure(); //configuration.AddAssembly(typeof(Product).Assembly); _sessionFactory = configuration.BuildSessionFactory(); } return _sessionFactory; } } public static ISession OpenSession() { return SessionFactory.OpenSession(); } } } 6,编写操作类及接口,操作类即是引用上面的helper类进行数据库的操作。 1)CRUD操作: using (ISession session = NHibernateHelper.OpenSession()) using (ITransaction transaction = session.BeginTransaction()) { session.Update(product); //session.Save(product);session.Delete(product); transaction.Commit(); } 2)查询 * 据关键字查询:session.Get(productId); * 据其它属性查询 * 返回一个值:session.CreateCriteria(typeof(Product)).Add(Restrictions.Eq("Name", name)).UniqueResult(); * 返回一个集合:session.CreateCriteria(typeof(Product)).Add(Restrictions.Eq("Name", name)).List();