好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

NHibernate+Oracle10g搭建一个项目架构全程解析(三)

五、 使用 NHibernate 编写持久层代码 1 .使用 Nhibernate 的七个基本步骤: 下面以持久化一个对象为例简单介绍这七个步骤 : //1.构造配置对象 Configuration config = new Configuration().Configure(); //2.构造SessionFactory对象 ISessionFactory sessi

五、 使用 NHibernate 编写持久层代码

1 .使用 Nhibernate 的七个基本步骤:

下面以持久化一个对象为例简单介绍这七个步骤 :

//1.构造配置对象 Configuration config = new Configuration().Configure(); //2.构造SessionFactory对象 ISessionFactory sessionFactory = config.BuildSessionFactory(); ISession session = null; ITransaction tx = null; try { //3.打开Session session = sessionFactory.OpenSession(); //4.打开事务 tx = session.BeginTransaction(); //5.处理持久化业务 session.Persist(obj); //6.提交事务 tx.Commit(); } catch { //6.回滚事务 tx.Rollback(); throw; } finally { //7.关闭Session if (session != null) { session.Close(); } }

2. 关于 Nhibernate 的很多基础理论,你可能要专门花时间学习,我这儿只针对学习过 NHibernate 的人了 ,

为了减化代码编写,下面是我对持久层代码的封装:

第一个类: HibernateSessionFactory:

namespace OfficeDAL { public class HibernateSessionFactory { const String CONFIG_FILE = "hibernate.cfg.xml"; const String ASSEMBLY = "BookShopModel"; static Configuration config = null; static ISessionFactory sessionFactory = null; /// /// 构造方法(相当于Java的静态代码块) /// static HibernateSessionFactory() { //config = new Configuration().Configure(CONFIG_FILE).AddAssembly(ASSEMBLY); //config = new Configuration().AddAssembly(ASSEMBLY); config = new Configuration().Configure(); sessionFactory = config.BuildSessionFactory(); } /// /// 得到SessionFactory /// /// public static ISessionFactory GetSessionFactory() { return sessionFactory; } /// /// 获得Session /// /// public static ISession GetSession() { return sessionFactory.OpenSession(); } } }

第二个类: BaseService, 所有 Service 类的基础类

由于这个类涉及分页,而关于分页的实体定义我放在另一个项目 (OfficeModel) 当中的

因此我先对这里的实体作一些解释:

NCondition :封装分页条件的类

namespace OffficeModel.Pagination { public class NCondition { private String _propertyName; public String PropertyName { get { return _propertyName; } set { _propertyName = value; } } private Operation _operate; public Operation Operate { get { return _operate; } set { _operate = value; } } private Object _propertyValue; public Object PropertyValue { get { return _propertyValue; } set { _propertyValue = value; } } public NCondition() { } public NCondition(String propertyName,Operation op,object propertyValue) { this._propertyName = propertyName; this._operate = op; this._propertyValue = propertyValue; } } }

Operation :封装比较操作的枚举 namespace OffficeModel.Pagination { public enum Operation { GT, LT, GE, LE, NE, EQ, LIKE, BETWEEN, IN } }

Order :封装排序的类

namespace OffficeModel.Pagination { public class NOrder { public enum OrderDirection { ASC, DESC } private String _propertyName; public String PropertyName { get { return _propertyName; } set { _propertyName = value; } } private OrderDirection _orderType; public OrderDirection OrderType { get { return _orderType; } set { _orderType = value; } } public NOrder() { } public NOrder(String propertyName,OrderDirection orderType) { this._propertyName = propertyName; this._orderType = orderType; } } }

PageInfo :封装分页信息的类

namespace OffficeModel.Pagination { public class PageInfo { public PageInfo() { } public PageInfo(Type entityType,int pageIndex) { this._entityType = entityType; this._pageIndex = pageIndex; } public PageInfo(Type entityType, int pageIndex,params NCondition[] conditions) { this._entityType = entityType; this._pageIndex = pageIndex; this._conditions = conditions; } public PageInfo(Type entityType, int pageIndex, NCondition[] conditions,NOrder[] orders) { this._entityType = entityType; this._pageIndex = pageIndex; this._conditions = conditions; this._orderFields = orders; } private Type _entityType;//类 public Type EntityType { get { return _entityType; } set { _entityType = value; } } private int _pageIndex = 1;//页号 public int PageIndex { get { return _pageIndex; } set { _pageIndex = value; } } private NCondition[] _conditions;//条件 public NCondition[] Conditions { get { return _conditions; } set { _conditions = value; } } private NOrder[] _orderFields;//排序 public NOrder[] OrderFields { get { return _orderFields; } set { _orderFields = value; } } private int pageSize = 10; public int PageSize { get { return pageSize; } set { pageSize = value; } } private int _recordCount; public int RecordCount { get { return _recordCount; } set { _recordCount = value; } } private int pageCount; public int PageCount { get { return pageCount; } set { pageCount = value; } } private System.Collections.IList list; public IList List { get { return list; } set { list = value; } } } }

下面终于回到最为关注的 BaseService 类,该类用于定义一些较为通用的方法,持久层其它类均继承自该类

using System; using System.Collections.Generic; using System.Text; using NHibernate; using OffficeModel.Pagination; using NHibernate.Criterion; using System.Collections; using log4net; namespace OfficeDAL { public class BaseService { protected ILog log = LogManager.GetLogger(typeof(BaseService)); protected ISession GetSession() { log.Info("Office :Session"); return HibernateSessionFactory.GetSession(); } /// /// 保存 /// /// public void Persist(Object obj) { ISession session = null; ITransaction tx = null; try { session = HibernateSessionFactory.GetSession(); tx = session.BeginTransaction(); session.Persist(obj); tx.Commit(); } catch { tx.Rollback(); throw; } finally { session.Close(); } } /// /// 删除对象 /// /// public void Remove(Object obj) { ISession session = null; ITransaction tx = null; try { session = HibernateSessionFactory.GetSession(); tx = session.BeginTransaction(); session.Delete(obj); tx.Commit(); } catch { tx.Rollback(); throw; } finally { session.Close(); } } /// /// 查询所有 /// /// /// /// public IList findAll () where T:new() { log.Info("Office: BaseService FindAll"); ISession session = null; try { session = HibernateSessionFactory.GetSession(); return session.CreateCriteria(typeof(T)).List (); } finally { session.Close(); } } /// /// 查询所有 /// /// /// /// public IList GetAll(Type entityType) { ISession session = null; try { session = HibernateSessionFactory.GetSession(); return session.CreateCriteria(entityType).List(); } finally { session.Close(); } } /// /// 根据对象oid进行查询 /// /// /// /// public T findById (object oid) where T:new() { ISession session = null; try { session = HibernateSessionFactory.GetSession(); return session.Get (oid); } finally { if (session != null) { session.Close(); } } } /// /// 修改对象 /// /// public void Update(object obj) { using (ISession session = HibernateSessionFactory.GetSession()) { session.Update(obj); session.Close(); } } public void DoPager(PageInfo pi) { log.Info("Office: DoPager"); if (pi.EntityType == null) { throw new Exception("分页类名不能为空"); } using (ISession session = HibernateSessionFactory.GetSession()) { ICriteria qbc = session.CreateCriteria(pi.EntityType); //总条数 qbc.SetProjection(NHibernate.Criterion.Projections.RowCount()); prepareConditions(qbc, pi.Conditions); pi.RecordCount = qbc .SetMaxResults(1) .UniqueResult (); //总页数 pi.PageCount = pi.RecordCount % pi.PageSize == 0? pi.RecordCount / pi.PageSize: pi.RecordCount / pi.PageSize + 1; //qbc.SetProjection(null); //分页结果 ICriteria _qbc = session.CreateCriteria(pi.EntityType); prepareConditions(_qbc, pi.Conditions); //设置排序 prepareOrder(_qbc, pi.OrderFields); //分页结果 pi.List = _qbc .SetFirstResult((pi.PageIndex - 1) * pi.PageSize) .SetMaxResults(pi.PageSize) .List(); } } /// /// 处理条件 /// /// /// private void prepareConditions(ICriteria qbc,params NCondition[] conditions) { if (qbc == null || conditions == null || conditions.Length == 0) { return; } foreach (NCondition condition in conditions) { switch (condition.Operate) { case Operation.EQ: qbc.Add(Expression.Eq(condition.PropertyName, condition.PropertyValue)); break; case Operation.GT: qbc.Add(Expression.Gt(condition.PropertyName, condition.PropertyValue)); break; case Operation.LT: qbc.Add(Expression.Lt(condition.PropertyName, condition.PropertyValue)); break; case Operation.GE: qbc.Add(Expression.Ge(condition.PropertyName, condition.PropertyValue)); break; case Operation.LE: qbc.Add(Expression.Le(condition.PropertyName, condition.PropertyValue)); break; case Operation.NE: qbc.Add(Expression.Not( Expression.Eq(condition.PropertyName, condition.PropertyValue) )); break; case Operation.BETWEEN: qbc.Add(Expression.Between( condition.PropertyName, (condition.PropertyValue as Object[])[0], (condition.PropertyValue as Object[])[1] ) ); break; case Operation.LIKE: qbc.Add(Expression.Like( condition.PropertyName, condition.PropertyValue.ToString(), MatchMode.Anywhere ) ); break; case Operation.IN: qbc.Add(Expression.In(condition.PropertyName, condition.PropertyValue as object[])); break; } } } /// /// 处理排序 /// /// /// private void prepareOrder(ICriteria qbc, params OffficeModel.Pagination.NOrder[] orderFields) { if (qbc == null || orderFields == null || orderFields.Length == 0) { return; } foreach (OffficeModel.Pagination.NOrder order in orderFields) { qbc.AddOrder( order.OrderType == OffficeModel.Pagination.NOrder.OrderDirection.ASC ? Order.Asc(order.PropertyName) : Order.Desc(order.PropertyName) ); } } /// /// 根据单个属性查询对象 /// /// /// /// /// public T FindByProperty (String propertyName,Object propertyValue) { using (ISession session = HibernateSessionFactory.GetSession()) { return session .CreateCriteria(typeof(T)) .Add(Restrictions.Eq(propertyName, propertyValue)) .SetMaxResults(1) .UniqueResult (); } } public T FindByProperty (String[] propertyNames,Object[] propertyValues) { if (propertyNames == null || propertyValues == null || propertyNames.Length == 0 || propertyValues.Length == 0 || propertyNames.Length != propertyValues.Length) { return default(T); } using (ISession session = HibernateSessionFactory.GetSession()) { ICriteria qbc = session.CreateCriteria(typeof(T)); for (int i = 0; i (); } } } }

时间关系,以上类注释较少,请多包涵,如有需要,可以相互探讨.

查看更多关于NHibernate+Oracle10g搭建一个项目架构全程解析(三)的详细内容...

  阅读:43次