现在的位置: 首页 > 综合 > 正文

nhibernate 的增删改查集成类

2012年11月11日 ⁄ 综合 ⁄ 共 1768字 ⁄ 字号 评论关闭

using System;
using System.Data;
using System.Web;
using NHibernate;
using System.Collections;

    public class DBobject
    {
        NHibernate.Cfg.Configuration config = null;
        ISessionFactory factory = null;
        ISession session = null;
        ITransaction trans = null;
        public DBobject()
        {
             config = new NHibernate.Cfg.Configuration().Configure();
            ////通过配置对象来产生一个SessionFactory对象,这是一个Session工厂,
            ////那么Session是用来干什么的呢?一个Session就是由NHibernate封装
            ////的工作单元,我们可以近似地认为它起到ADO.Net中Connection的作用。
             factory = config.BuildSessionFactory();
             session = factory.OpenSession();
            ////这里,开启一个由NHibernate封装的事务,当然,在这里最终代表
            ////的还是一个真实的数据库事务,但是我们已经不需要再区分到底是
            trans = session.BeginTransaction();
        }
        public bool Save(object obj)
        {
            try
            {
                session.Save(obj);
                trans.Commit();
                return true;
            }
            catch (Exception ex)
            {
                trans.Rollback();
                return false;
            }
        }
        public bool Update(object obj,int id)
        {
            try
            {
                session.Update(obj,id);
                trans.Commit();
                return true;
            }
            catch (Exception ex)
            {
                trans.Rollback();
                return false;
            }
        }
        public bool Delete(object obj, int id)
        {
            try
            {
                session.Delete(session.Get(obj.ToString(),id));
                trans.Commit();
                return true;
            }
            catch (Exception ex)
            {
                trans.Rollback();
                return false;
            }
        }
        public IList getList(string sql)
        {
            return session.CreateQuery(sql).List();
        }
    }

抱歉!评论已关闭.