1. 在 NHibernate 中使用事务, 主要代码如下:

        #region 事务

        public IList<Customer> GetAll()
{
// 开启事物
using (ITransaction tx = _session.BeginTransaction())
{
try
{
//提交事务
tx.Commit();
return null; }
catch (HibernateException ex)
{
  // 回滚事务
tx.Rollback();
throw ex ;
} }
} #endregion

2. 使用N NHibernate 进行CRUD 操作

      #region  添加、 删除、更新对象

        public int Add(Customer model)
{ int id =(int) _session.Save(model);
_session.Flush(); return id;
} public void Delete ( Customer model)
{ _session.Delete(model); _session.Flush(); } public void Update( Customer model)
{
// 更新
_session.Update(model); // 更新或保存 •检查这个对象是否已经存在Session中。如果对象不在,调用Save(object)来保存。如果对象存在,检查这个对象是否改变了。 如果对象改变,调用Update(object)来更新。 //_session.SaveOrUpdate(model); _session.Flush(); } #endregion

3. 带条件的查询

     #region 条件查询 (Criteria Query)

        // 创建 Criteria 实例 使用ISession接口的CreateCriteria方法创建了NHibernate.ICriteria接口一个特定的持久化类的查询实例,也可以说ISession是用来制造Criteria实例的工厂
public IList<Customer> Creater()
{ ICriteria cria = _session.CreateCriteria(typeof(Customer)); cria.SetMaxResults(50); IList<Customer> list = cria.List<Customer>(); return list; } // 结果集限制数据
//使用ICriteria接口提供的Add方法添加Restrictions类中约束表达式可以限制一些结果集的作用。
public IList<Customer> Norrawing()
{ IList<Customer> customers = _session.CreateCriteria(typeof(Customer))
.Add(Restrictions.Like("FirstName","y%"))// 查询 FirstName like y%
.Add(Restrictions.Eq("FirstName", "yang ")) // 查询 FirstName=Yang
.Add(Restrictions.Between("LastName","%m","_n")) // 查询 LastName between %m _n
.List<Customer>(); return customers; } // 结果集排序
// 使用ICriteria.Order对结果集排序,第二个参数true代表asc,false代表desc。例如下面例子查询Customer对象按FirstName降序、Lastname升序。
public IList<Customer> Orderss()
{ IList<Customer> customers = _session.CreateCriteria(typeof(Customer))
.Add(Restrictions.Like("FristName","yangming"))
.AddOrder(new Order("FirstName",false)) /// FirstName 降序排序
.AddOrder(new Order("LastName",true)) // LastName 升序排序
.List<Customer>(); return customers; } /*
* 条件查询同样支持关联查询、动态关联抓取(在介绍一对多,多对多关系中阐述),投影、聚合和分组,离线(detached)查询和子查询是2.0版新增加的内容
* */ // 根据 示例查询(Query By Example) //根据示例查询(QBE,Query By Example)是条件查询的一种特殊情况,NHibernate.Criterion.Example类根据你指定的实例创造查询条件。其典型的用法:创建一个Example实例;在Example实例上设置值;根据Example和设置NHibernate返回其对象集合。 public IList<Customer> Query()
{ Customer customer = new Customer { Firstname="yangyang", Lastname="wang"}; return _session.CreateCriteria(typeof(Customer))
.Add(Example.Create(customer))
.List<Customer>(); } //可以自行调整Example使之更实用:
public IList<Customer> Query(Customer customer)
{ Example exa = Example.Create(customer)
.IgnoreCase()
.EnableLike()
.SetEscapeCharacter('&'); return _session.CreateCriteria(typeof(Customer))
.Add(exa)
.List<Customer>(); } #endregion #region 查询 NHibernate查询语言(HQL) public IList<Customer> ListAll()
{ return _session.CreateCriteria(" from Customer ")
.List<Customer>(); } public IList<Customer> ListAll2()
{ return _session.CreateCriteria(" From Customer as c ")
.List<Customer>(); // group by 子句
//return _session.CreateCriteria("select * from Customer group by firstname ")
//.List<Customer>(); // distinct 子句
// return _session.CreateQuery("select distinct c.Firstname from Customer c")
//.List<Customer>(); // where 子句 //return _session.CreateQuery("from Customer c where c.Firstname='YJing'")
// .List<Customer>(); // 带参数的 where 子句
// // return _session.CreateQuery("from Customer c where c.CustomerId > :cid")
//.SetInt32("cid", 1)
//.List<Customer>(); } #endregion

3. 用 NHibernate 进行分页查询

        #region  分页查询

         ISessionFactory SessionFactory;

         // 分页功能
public IList<Customer> GetAll(int currentPage, int pageSize)
{
// 获取当前 session
ISession curSession = SessionFactory.GetCurrentSession(); ICriteria cria = _session.CreateCriteria(typeof(Customer)); // 分页
var model = cria.SetFetchSize(pageSize).SetFirstResult(currentPage).List<Customer>(); return model; } // 分页查询
//在Nhibernate里实现分页用 SetFirstResult 和SetMaxResults实现,SetFirstResult 简单的理解就是从第几条记录开始,SetMaxResults是取几条记录
private IList<Customer> GetRecord(IList<ICriterion> queryConditions, int pageIndex, int pageSize, string orderField, bool isAscending)
{ ICriteria criteria = _session.CreateCriteria(typeof(Customer)); foreach (ICriterion cri in queryConditions)
{ criteria.Add(cri); } //记录总数
int skipCount = (pageIndex - 1) * pageSize; criteria.AddOrder(new Order(orderField, isAscending)); criteria.SetFirstResult(skipCount).SetMaxResults(pageSize); return criteria.List<Customer>(); //SQL查询
//IList<Customer> customerList = Session.CreateSQLQuery("SELECT * FROM Customer")
// .SetFirstResult(pageStart*pageLimit)
// .SetMaxResults(pageLimit)
// .SetResultTransformer(Transformers.AliasToBean<Customer>()).List<Customer>();
//return customerList; IList<Customer> customers = _session.CreateSQLQuery("")
.SetFirstResult(pageIndex * pageSize)
.SetMaxResults(pageSize)
.SetResultTransformer (NHibernate.Transform.Transformers.AliasToBean<Customer>()).List<Customer>(); return customers;
} #endregion

跟我学 NHibernate (二)的更多相关文章

  1. Mina、Netty、Twisted一起学(二):TCP消息边界问题及按行分割消息

    在TCP连接开始到结束连接,之间可能会多次传输数据,也就是服务器和客户端之间可能会在连接过程中互相传输多条消息.理想状况是一方每发送一条消息,另一方就立即接收到一条,也就是一次write对应一次rea ...

  2. 【原创】只学到二维数组和结构体,不用链表也能写一个C贪食蛇?(四)

    全系列Index: [原创]只学到二维数组和结构体,不用链表也能写一个C贪食蛇?(一) [原创]只学到二维数组和结构体,不用链表也能写一个C贪食蛇?(二) [原创]只学到二维数组和结构体,不用链表也能 ...

  3. 从头开始学JavaScript (二)——变量及其作用域

    原文:从头开始学JavaScript (二)--变量及其作用域 一.变量 ECMAscript变量是松散型变量,所谓松散型变量,就是变量名称可以保存任何类型的数据,每个变量仅仅是一个用于保存值的占位符 ...

  4. 大家一起来学 NHibernate+NUnit (VS2012+SQL Server2008)

    大家一起来学 NHibernate+NUnit (VS2012+SQL Server2008) 分类: C#2013-08-10 18:47 1589人阅读 评论(5) 收藏 举报 NHibernat ...

  5. JavaWeb从0开始学(二)-----JSP基本语法与编译指令

    在上一节中我们学习了如何搭建一个简单的Web应用,并且已经知晓了一个JSP页面主要由静态的HTML内容和动态的Java脚本共同组成.JSP的基本语法共有JSP注释.JSP声明.输出JSP表达式与JSP ...

  6. .Net应该学什么怎么学(二)

    更新时间:2012年06月05日18时23分 来源:传智播客.Net 接上篇<[我来解惑].Net应该学什么怎么学(一)>. 二.C#面向对象基础 初学者学面向对象的时候没必要(也做不到) ...

  7. 菜鸟学Nhibernate 之路---(1)

    首先说一下我为什么要学这个Nhibernate,现在在公司做项目后台的逻辑层都是用动软生成的简单三层,搞来搞去都是这些东西,代码冗余量很大,每个类方法基本上都一样,真是纯正的码农,虽然后来我也尝试使用 ...

  8. 从零开始学MySQL(二)

    鉴于上节篇幅以安装为主,因此对于调用mysql所需要使用的“命令”只是略微提及.随之而来就会带给读者诸多不解了,因为你会思考,这串长长的字符到底有什么特殊的含义呢?聪明的你可能早就抱着好奇心去“摆渡” ...

  9. 重学STM32----(二)

    前几天买了个蓝牙模块,昨天到来了,就打算来研究研究蓝牙.看了蓝牙模块的资料,知道通讯需要串口,那肯定要先写一个串口程序了.要是用库函数写,10多分钟可能就会搞定,但是这就违背我的初衷了,所以就不知天高 ...

随机推荐

  1. android下asynchttp库对于session的支持

    默认asynchttp库不支持session,需要用户配置下cookie来处理,直接贴支持session的代码 package example.com.sessiontest; import andr ...

  2. Linux从逻辑地址到物理地址

    转自:http://blog.chinaunix.net/uid-24774106-id-3427836.html 我们都知道,动态共享库里面的函数的共享的,这也是动态库的优势所在,就是节省内存.C ...

  3. 328. Odd Even Linked List

    Given a singly linked list, group all odd nodes together followed by the even nodes. Please note her ...

  4. Mysql分区技术

    注:分区的语法可以看手册中有详细的写法和例子: show plugins; 此命令查看可有partition这个选项,有则mysql支持分区,没有的话,就可以升级一下mysql 实时监控一个命令执行情 ...

  5. postgresql plpythonu例子

    以下代码仅作为参考之用 select md5, crc32, record->'UserModerAnalysis'->'base_info'->'file_malware' as ...

  6. org.hibernate.id.IdentifierGenerationException: Unknown integral data type for ids : java.lang.String

    org.hibernate.id.IdentifierGenerationException: Unknown integral data type for ids : java.lang.Strin ...

  7. ADF_Database Develop系列1_通过UML数据库开发之建Logical UML Class Model

    2013-05-01 Created By BaoXinjian

  8. Red hat 5挂载U盘

    装在虚拟机上的Linux 一.挂载U盘                                                                                  ...

  9. python中的生成器

    什么是生成器? 生成器是一个包含了特殊关键字yield的函数.当被调用的时候,生成器函数返回一个生成器.可以使用send,throw,close方法让生成器和外界交互. 生成器也是迭代器,但是它不仅仅 ...

  10. jQuery实现的鼠标滑过切换图片代码实例

    jQuery实现的鼠标滑过切换图片代码实例:有时候网页需要这样的简单效果,那就是当鼠标滑过默认图片的时候,能够实现图片的切换,可能在实际应用中,往往没有这么简单,不过大家可以自行扩展一下,下面简单介绍 ...