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

1)CRUD操作:
using (ISession session = NHibernateHelper.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Update(product); //session.Save(product);session.Delete(product); 或者_session.SaveOrUpdate(c);
transaction.Commit();
}

在NHibernate中提供了三种查询方式给我们选择:NHibernate查询语言(HQL,NHibernate Query Language)、条件查询(Criteria API,Criteria Query)、(根据示例查询(QBE,Query By Example)是条件查询的一种特殊情况)、原生SQL(Literal SQL,T-SQL、PL/SQL)。

2)简单查询–条件查询Criteria Query

  • 据关键字查询:session.Get<Product>(productId);
  • 据其它属性查询
  • 返回一个值:session.CreateCriteria(typeof(Product)).Add(Restrictions.Eq(“Name”, name)).UniqueResult<Product>();
  • 返回一个集合:session.CreateCriteria(typeof(Product)).Add(Restrictions.Eq(“Name”, name)).List<Product>();
  • 除了用Eq外,还可用like,between等

3)SQL语句–HQL查询

  • From子句: return _session.CreateQuery(“from Customer”) .List<Customer>();
  • select 子句 :
    
  • return _session.CreateQuery("select c.Firstname, count(c.Firstname) from Customer c group by c.Firstname").List<object[]>();
    
  • where子句:return _session.CreateQuery(“from Customer c where c.Firstname=’YJing'”) .List<Customer>();
    注:显示的名字为实体名而不是表名
  •   order by子句:return _session.CreateQuery("from Customer c order by c.Firstname asc,c.Lastname desc").List<Customer>();
  • group by子句:
      return _session.CreateQuery("select c.Firstname, count(c.Firstname) from Customer c group by c.Firstname").List<object[]>();
  • 参数传递:
     return _session.CreateQuery("from Customer c where c.Firstname=:fn").SetString("fn", firstname).List<Customer>();


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

1,连接数据库:
var configuration = new Configuration();
configuration.Configure(); //自动探索hibernate.cfg.xml或web.config中的nhibernate
configuration.AddAssembly(typeof(Product).Assembly); //指定加载哪个程序集,若不写,则默认加载工程本身
2, 连接完数据库后创建Session: _sessionFactory = configuration.BuildSessionFactory(); SessionFactory.OpenSession();
3,利用Session完之后,因是延迟加载,需用 _Session.Flush(); 提交更新,或者待Session销毁时自动提交,如:
using (ISession session = NHibernateHelper.OpenSession())
{
session.Save(user);
}


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();


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
	先编写持久化类和映射文件,然后使用SchemaExport工具生成数据库架构。这样的方式就是领域驱动设计/开发。
好处:当领域模型需要改变,只需修改NHibernate结构和应用程序,不需要修改数据库架构,只要利用SchemaExport工具重新生成数据库架构就可以了。但是使用数据库只是其中一种方式,我们也可以使用XML文件来存储数据。

	NHibernate的hbm2dll提供SchemaExport工具:给定一个连接字符串和映射文件,不需输入其他东西就可以按照持久化类和映射文件自动生成数据库架构
SchemaExport工具就是把DDL脚本输出到标准输出,同时/或者执行DDL语句。SchemaExport工具提供了三个方法,分别是 Drop()、Create()、Execute(),前两个方法实质是调用Execute()方法。通常使用Execute()方法来生成数据库架构的。

如:      
	var cfg = new Configuration();

	cfg.Configure(); //自动寻找hibernate.cfg.xml文件读取数据库连接信息

	cfg.AddAssembly(typeof(Product).Assembly); //根据Product类查找Product.hbm.xml

	new SchemaExport(cfg).Execute(true, true, false);
	//第一个true输出sql创建语句到控制台,第二个用来先删除后创建