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
本博客是自己在学习和工作途中的积累与总结,仅供自己参考,也欢迎大家转载,转载时请注明出处。
浙公网安备 33010602011771号