频道栏目
首页 > 资讯 > 其他 > 正文

MyBatisNet数据操作类教程

18-01-20        来源:[db:作者]  
收藏   我要投稿
1
using System;
using System.Collections.Generic;
using System.Collections;
using System.Data;
using System.Linq;
using MT.Framework.DataOperation;
using MT.Framework.DataOperation.Sequences;
using MT.Framework.Logs;
using MyBatis.DataMapper;
using MyBatis.DataMapper.Exceptions;
using MyBatis.DataMapper.Session;
using MyBatis.DataMapper.Session.Transaction;

namespace MT.Frame.DAL.DataAccessLayer
{
    /// 
    /// MyBatisNet数据操作类
    /// 
    public class DatabaseMyBatis : IDatabaseMyBatis, IDisposable
    {

        private string _errorInfo;
        /// 
        /// 错误提示
        /// 
        public string ErrorInfo
        {
            get { return _errorInfo; }
            set { _errorInfo = value; }
        }
        private DatabaseMybatisBuilder _dataBase;
        private IDataMapper _dataMapper;
        /// 
        /// SqlMapper对象
        /// 
        protected IDataMapper DataMapper
        {
            get { return _dataMapper; }
            set
            {
                _dataMapper = value;
                _sessionFactory = ((IModelStoreAccessor)_dataMapper).ModelStore.SessionFactory;
            }
        }
        /// 
        /// Session
        /// 
        private ISession _session;
        /// 
        /// _transaction
        /// 
        private ITransaction _transaction;
        /// 
        /// 
        /// 
        private ISessionFactory _sessionFactory;

        private string _connectionString;
        /// 
        /// 数据库连接字符串
        /// 
        public string ConnectionString
        {
            get { return _connectionString; }
            set { _connectionString = value; }
        }
        /// 
        /// 序号生成器
        /// 
        public ISequences Sequences { get; private set; }

        #region 构造函数
        /// 
        /// 构造函数
        /// 
        ///
        public DatabaseMyBatis(string connectionString)
        {
            ConnectionString = connectionString;
            _dataBase = new DatabaseMybatisBuilder();
            DataMapper = _dataBase.GetMapper();
            //_sessionFactory = _dataBase.SessionFactory;
            _sessionFactory.DataSource.ConnectionString = connectionString;
            Sequences = new Sequence(ConnectionString);
            // SqlMapperForSequence = _dataBase.GetMapper("SqlMapSequence.config");


        }
        /// 
        /// 
        /// 
        public DatabaseMyBatis()
        {
            _dataBase = new DatabaseMybatisBuilder();
            DataMapper = _dataBase.GetMapper();
            //  _sessionFactory = _dataBase.SessionFactory;
            // SqlMapperForSequence = _dataBase.GetMapper("SqlMapSequence.config");

        }

        /// 
        /// 
        /// 
        ///
        ///
        public DatabaseMyBatis(string connectionString, string sqlMapFileName)
        {
            // _application = application;
            _dataBase = new DatabaseMybatisBuilder();
            DataMapper = _dataBase.GetMapper2(sqlMapFileName);
            ConnectionString = connectionString;
            // _sessionFactory = _dataBase.SessionFactory;
            _sessionFactory.DataSource.ConnectionString = connectionString;
            //Sequences = new Sequence(ConnectionString);

        }


        //public DatabaseMyBatis( IDataMapper idataMapper)
        //{
        //   // this._application = application;
        //    _dataBase = new DatabaseMybatisBuilder();
        //    _dataMapper = idataMapper;

        //}

        #endregion

        /// 
        /// 连接到数据,并作相应的初始化
        /// 
        /// 
        public Boolean ConnectAccessDb()
        {
            try
            {
                ISession session = _sessionFactory.OpenSession();
                if (session == null)
                {
                    return false;
                }
                session.OpenConnection();
                session.Close();
                return true;
            }
            catch (DataMapperException e)
            {
                ErrorInfo = @"打开数据库出错:\n" + e.InnerException.Message;
                return false;
            }
            catch (Exception ex)
            {
                ErrorInfo = string.Format("初始化DataMapper对象出错:\n{0}", ex.Message);
                return false;
            }

        }
        /// 
        /// 连接到数据库,并作相应的初始化
        /// 
        /// 
        public Boolean ConnectDb()
        {
            try
            {
                if (_dataBase == null)
                {
                    _dataBase = new DatabaseMybatisBuilder();
                }
                if (DataMapper == null)
                {
                    DataMapper = _dataBase.GetMapper();
                }
                //if (SqlMapperForSequence == null)
                //{
                //    SqlMapperForSequence = _dataBase.GetMapper("SqlMapSequence.config");
                //}
                //  _seq = new SeqNumber(SqlMapperForSequence);

                using (ISession session = _sessionFactory.OpenSession())
                {
                    if (session == null)
                    {
                        return false;
                    }
                    using (var con = session.OpenConnection())
                    {
                        con.Close();
                        con.Dispose();
                    }

                    session.Close();
                    session.Dispose();
                }
                return true;
            }
            catch (DataMapperException e)
            {
                ErrorInfo = string.Format("打开数据库出错:\n{0}", e.InnerException.Message);
                return false;
            }
            catch (Exception ex)
            {
                ErrorInfo = @"初始化DataMapper对象出错:\r" + ex.Message;
                return false;
            }

        }

        /// 
        /// 
        /// 
        /// 
        public IDataMapper GetMapper()
        {
            return _dataMapper;
        }

        #region 数据操作方法
        #region 事物控制方法
        /// 
        /// 开始一个会话
        /// 
        private void BeginSession()
        {
            if (_session != null)
            {
                CloseSession();
            }
            _session = _sessionFactory.OpenSession();
        }
        /// 
        /// 关闭一个会话
        /// 
        private void CloseSession()
        {
            if (_session != null)
            {
                if (_session.Connection != null)
                {
                    _session.Connection.Close();
                    _session.Connection.Dispose();
                }
                _session.Close();
                _session.Dispose();
                _session = null;
            }
        }
        /// 
        /// 开启一个事物
        /// 
        public void BeginTransaction()
        {
            IsAutoCommit = false;
            BeginSession();
            _transaction = _session.BeginTransaction();

        }
        /// 
        /// 提交一个事物
        /// 
        public void CommitTransaction()
        {
            _transaction.Commit();
            CloseSession();
            IsAutoCommit = true;

        }
        /// 
        /// 回滚一个事件
        /// 
        public void RollBackTransaction()
        {
            _transaction.Rollback();
            CloseSession();
            IsAutoCommit = true;

        }
        #endregion
        #endregion
        /// 
        /// 
        /// 
        ///
        ///
        /// 
        public IList QueryForIList(string statementName, object parameterObject)
        {
            using (var session = _sessionFactory.OpenSession())
            {
                using (var con = session.OpenConnection())
                {
                    try
                    {
                        var list = _dataMapper.QueryForList(statementName, parameterObject);
                        con.Close();
                        con.Dispose();
                        if (session.Connection != null)
                        {
                            session.Connection.Close();
                            session.Connection.Dispose();
                        }
                        session.Close();
                        session.Dispose();
                        return list;
                    }
                    catch (Exception ex)
                    {
                        session.Close();
                        session.Dispose();
                        ErrorInfo = ex.Message;
                        throw new Exception(ex.Message, ex);
                    }
                    finally
                    {
                        if (session.Connection != null)
                        {
                            session.Connection.Close();
                            session.Connection.Dispose();
                        }
                        session.Close();
                        session.Dispose();
                    }
                }
            }
        }
        /// 
        /// 
        /// 
        /// 
        ///
        ///
        /// 
        public IList QueryForList(string statementName, object parameterObject)
        {
            using (var session = _sessionFactory.OpenSession())
            {
                using (var con = session.OpenConnection())
                {
                    try
                    {
                        var list = _dataMapper.QueryForList(statementName, parameterObject);
                        con.Close();
                        con.Dispose();
                        if (session.Connection != null)
                        {
                            session.Connection.Close();
                            session.Connection.Dispose();
                        }
                        session.Close();
                        session.Dispose();
                        return list;

                    }
                    catch (Exception ex)
                    {
                        if (session.Connection != null)
                        {
                            session.Connection.Close();
                            session.Connection.Dispose();
                        }
                        session.Close();
                        session.Dispose();
                        ErrorInfo = ex.Message;
                        throw new Exception(ex.Message, ex);
                    }
                    finally
                    {
                        if (session.Connection != null)
                        {
                            session.Connection.Close();
                            session.Connection.Dispose();
                        }
                        session.Close();
                        session.Dispose();
                    }
                }
            }
        }
        /// 
        /// 
        /// 
        ///
        ///
        /// 
        public IList QueryForList(string statementName, object parameterObject)
        {
            using (var session = _sessionFactory.OpenSession())
            {
                using (var con = session.OpenConnection())
                {
                    try
                    {
                        var list = _dataMapper.QueryForList(statementName, parameterObject);
                        con.Close();
                        con.Dispose();
                        if (session.Connection != null)
                        {
                            session.Connection.Close();
                            session.Connection.Dispose();
                        }
                        session.Close();
                        session.Dispose();
                        return list;

                    }
                    catch (Exception ex)
                    {
                        if (session.Connection != null)
                        {
                            session.Connection.Close();
                            session.Connection.Dispose();
                        }
                        session.Close();
                        session.Dispose();
                        ErrorInfo = ex.Message;
                        throw new Exception(ex.Message, ex);
                    }
                    finally
                    {
                        if (session.Connection != null)
                        {
                            session.Connection.Close();
                            session.Connection.Dispose();
                        }
                        session.Close();
                        session.Dispose();
                    }
                }
            }
        }
        /// 
        /// 
        /// 
        ///
        ///
        /// 
        public object QueryForObject(string statementName, object parameterObject)
        {
            using (var session = _sessionFactory.OpenSession())
            {
                using (var con = session.OpenConnection())
                {
                    try
                    {
                        var obj = _dataMapper.QueryForObject(statementName, parameterObject);
                        con.Close();
                        con.Dispose();
                        if (session.Connection != null)
                        {
                            session.Connection.Close();
                            session.Connection.Dispose();
                        }
                        session.Close();
                        session.Dispose();
                        return obj;
                    }
                    catch (Exception ex)
                    {
                        if (session.Connection != null)
                        {
                            session.Connection.Close();
                            session.Connection.Dispose();
                        }
                        session.Close();
                        session.Dispose();
                        ErrorInfo = ex.Message;
                        throw new Exception(ex.Message, ex);
                    }
                    finally
                    {
                        if (session.Connection != null)
                        {
                            session.Connection.Close();
                            session.Connection.Dispose();
                        }
                        session.Close();
                        session.Dispose();
                    }
                }
            }
        }
        /// 
        /// 
        /// 
        /// 
        ///
        ///
        /// 
        public T QueryForObject(string statementName, object parameterObject)
        {
            using (var session = _sessionFactory.OpenSession())
            {
                using (var con = session.OpenConnection())
                {
                    try
                    {
                        var obj = _dataMapper.QueryForObject(statementName, parameterObject);
                        con.Close();
                        con.Dispose();
                        if (session.Connection != null)
                        {
                            session.Connection.Close();
                            session.Connection.Dispose();
                        }
                        session.Close();
                        session.Dispose();
                        return obj;
                    }
                    catch (Exception ex)
                    {
                        if (session.Connection != null)
                        {
                            session.Connection.Close();
                            session.Connection.Dispose();
                        }
                        session.Close();
                        session.Dispose();
                        ErrorInfo = ex.Message;
                        throw new Exception(ex.Message, ex);
                    }
                    finally
                    {
                        if (session.Connection != null)
                        {
                            session.Connection.Close();
                            session.Connection.Dispose();
                        }
                        session.Close();
                        session.Dispose();
                    }
                }
            }
        }
        /// 
        /// 
        /// 
        ///
        ///
        ///
        /// 
        public Boolean QueryForDataTable(out DataTable dt, string statementName, object parameterObject)
        {
            try
            {
                dt = new DataTable();
                IList list = QueryForList(statementName, parameterObject);
                // object iDictionary = sqlMapper.QueryForObject(statementName, parameterObject);
                if (list.Count <= 0)
                {

                    return false;
                }
                //此处遍历IList的结构并建立同样的DataTable
                System.Reflection.PropertyInfo[] p = list[0].GetType().GetProperties();
                // var a = list[0] as ArrayList;
                foreach (System.Reflection.PropertyInfo pi in p)
                {
                    Type colType = pi.PropertyType;

                    if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                    {

                        colType = colType.GetGenericArguments()[0];

                    }
                    // ReSharper disable once AssignNullToNotNullAttribute
                    dt.Columns.Add(pi.Name, Type.GetType(colType.ToString()));
                }

                for (int i = 0; i < list.Count; i++)
                {
                    // t1 = list[i];
                    IList tempList = new ArrayList();
                    //将IList中的一条记录写入ArrayList
                    foreach (var pi in p)
                    {
                        object oo = pi.GetValue(list[i], null);
                        tempList.Add(oo);
                    }

                    object[] itm = new object[p.Length];
                    //遍历ArrayList向object[]里放数据
                    for (int j = 0; j < tempList.Count; j++)
                    {
                        itm.SetValue(tempList[j], j);
                    }
                    //将object[]的内容放入DataTable
                    dt.LoadDataRow(itm, true);
                }
            }
            catch (Exception ex)
            {
                ErrorInfo = ex.Message;
                throw new Exception(ex.Message, ex);
            }
            return true;
        }
        /// 
        /// 
        /// 
        /// 
        ///
        ///
        ///
        /// 
        public Boolean QueryForDataTable(out DataTable dt, string statementName, object parameterObject)
        {
            dt = new DataTable();
            try
            {
                // dt = new DataTable();
                IList list = QueryForList(statementName, parameterObject);
                T t1;
                if (list.Count <= 0)
                {
                    //dt = getDataTableForClass(typeof(T).ToString());
                    dt = GetDataTableForClass();
                    return true;
                }
                //此处遍历IList的结构并建立同样的DataTable
                System.Reflection.PropertyInfo[] p = list[0].GetType().GetProperties();
                foreach (System.Reflection.PropertyInfo pi in p)
                {
                    Type type = typeof(T);
                    if (pi.DeclaringType != type)
                    {
                        continue;
                    }
                    Type colType = pi.PropertyType;
                    if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                    {

                        colType = colType.GetGenericArguments()[0];

                    }
                    // ReSharper disable once AssignNullToNotNullAttribute
                    dt.Columns.Add(pi.Name, Type.GetType(colType.ToString()));
                }

                for (int i = 0; i < list.Count; i++)
                {

                    t1 = list[i];
                    IList tempList = new ArrayList();
                    //int len = 0;
                    //将IList中的一条记录写入ArrayList
                    foreach (var pi in t1.GetType().GetProperties())
                    {
                        Type type1 = typeof(T);
                        if (pi.DeclaringType != type1)
                        {
                            continue;
                        }
                        object oo = pi.GetValue(t1, null);
                        tempList.Add(oo);

                    }

                    object[] itm = new object[tempList.Count];
                    //遍历ArrayList向object[]里放数据
                    for (int j = 0; j < tempList.Count; j++)
                    {
                        itm.SetValue(tempList[j], j);
                    }
                    //将object[]的内容放入DataTable
                    dt.LoadDataRow(itm, true);
                }
            }
            catch (Exception ex)
            {
                ErrorInfo = ex.Message;
                dt = GetDataTableForClass();
                //System.Windows.Forms.MessageBox.Show("数据查询出错:" + ex.Message, "查询错误", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                throw new Exception(ex.Message, ex);
                //return false;
            }
            return true;
        }
        /// 
        /// 
        /// 
        /// 
        /// 
        public DataTable GetDataTableForClass()
        {
            var dt = new DataTable();
            try
            {
                Type type = typeof(T);
                DataColumn dcl;

                foreach (var item in type.GetProperties())
                {

                    Type type1 = typeof(T);
                    if (item.DeclaringType != type1)
                    {
                        continue;
                    }
                    Type colType = item.PropertyType;
                    if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                    {

                        colType = colType.GetGenericArguments()[0];

                    }

                    dcl = new DataColumn(item.Name, colType);
                    dt.Columns.Add(dcl);

                }
                dt.TableName = type.Name;
            }
            catch (Exception ex)
            {
                ErrorInfo = ex.Message;
                throw new Exception(ex.Message, ex);
            }
            return dt;

        }
        /// 
        /// 
        /// 
        ///
        /// 
        public DataTable GetDataTableForClass(string parameterClass)
        {
            var dt = new DataTable();
            try
            {
                Type type = Type.GetType(parameterClass);
                if (type == null)
                {

                    throw new Exception("传入的类型【" + parameterClass + "】不存在!");
                }
                DataColumn dcl;

                foreach (var item in type.GetProperties())
                {
                    Type colType = item.PropertyType;
                    if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                    {

                        colType = colType.GetGenericArguments()[0];

                    }
                    dcl = new DataColumn(item.Name, colType);
                    dt.Columns.Add(dcl);

                }
                dt.TableName = type.Name;
            }
            catch (Exception ex)
            {
                ErrorInfo = ex.Message;
                throw new Exception(ex.Message, ex);
            }
            return dt;

        }

        /// 
        /// 
        /// 
        ///
        ///
        ///
        ///
        /// 
        public bool Insert(string statementName, T parameterObject, ref Nullable keyValue,
            out object returnValue)
        {
            object a;
            if (IsAutoCommit)
            {
                using (ISession session = _sessionFactory.OpenSession())
                {
                    using (ITransaction transaction = session.BeginTransaction())
                    {
                        try
                        {
                            a = _dataMapper.Insert(statementName, parameterObject);
                            keyValue = Convert.ToInt32(a);
                            returnValue = a;
                            transaction.Commit();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                        }
                        catch (Exception ex)
                        {
                            ErrorInfo = ex.Message;
                            transaction.Rollback();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                            returnValue = null;
                            return false;
                        }
                        finally
                        {
                            transaction.Complete();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                        }
                    }
                }
            }

            else
            {
                try
                {
                    a = _dataMapper.Insert(statementName, parameterObject);
                    keyValue = Convert.ToInt32(a);
                    returnValue = a;
                    return true;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message, ex);
                }

            }
            return true;
        }

        /// 
        /// 
        /// 
        ///
        ///
        ///
        /// 
        public bool Insert(string statementName, T parameterObject, out object returnValue)
        {
            if (IsAutoCommit)
            {
                using (ISession session = _sessionFactory.OpenSession())
                {
                    using (ITransaction transaction = session.BeginTransaction())
                    {
                        try
                        {
                            returnValue = _dataMapper.Insert(statementName, parameterObject);
                            transaction.Commit();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                        }
                        catch (Exception ex)
                        {
                            ErrorInfo = ex.Message;
                            transaction.Rollback();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                            returnValue = null;
                            return false;
                        }
                        finally
                        {
                            transaction.Complete();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                        }
                    }
                }
            }
            else
            {
                returnValue = _dataMapper.Insert(statementName, parameterObject);
            }
            return true;

        }
        /// 
        /// 
        /// 
        ///
        ///
        /// 
        public bool Insert(string statementName, IEnumerable parameterObjects)
        {

            if (IsAutoCommit)
            {
                using (ISession session = _sessionFactory.OpenSession())
                {
                    using (ITransaction transaction = session.BeginTransaction())
                    {
                        try
                        {
                            foreach (object parameterObject in parameterObjects)
                            {
                                _dataMapper.Insert(statementName, parameterObject);
                            }
                            transaction.Commit();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                        }
                        catch (Exception ex)
                        {
                            ErrorInfo = ex.Message;
                            transaction.Rollback();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                            return false;
                        }
                        finally
                        {
                            transaction.Complete();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                        }
                    }
                }
            }
            else
            {
                foreach (object parameterObject in parameterObjects)
                {
                    _dataMapper.Insert(statementName, parameterObject);
                }
            }
            return true;

        }

        /// 
        /// 更新单条数据
        /// 
        ///
        ///
        ///
        /// 
        public bool Update(string statementName, T parameterObject, out object returnValue)
        {
            if (IsAutoCommit)
            {
                using (ISession session = _sessionFactory.OpenSession())
                {
                    using (ITransaction transaction = session.BeginTransaction())
                    {
                        try
                        {
                            returnValue = _dataMapper.Update(statementName, parameterObject);
                            transaction.Commit();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                        }
                        catch (Exception ex)
                        {
                            ErrorInfo = ex.Message;
                            transaction.Rollback();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                            returnValue = null;
                            return false;
                        }
                        finally
                        {
                            transaction.Complete();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                        }
                    }
                }
            }
            else
            {
                returnValue = _dataMapper.Update(statementName, parameterObject);

            }
            return true;
        }
        /// 
        /// 更新一组数据
        /// 
        ///
        ///
        /// 
        public bool Update(string statementName, IEnumerable parameterObjects)
        {
            if (IsAutoCommit)
            {
                using (ISession session = _sessionFactory.OpenSession())
                {
                    using (ITransaction transaction = session.BeginTransaction())
                    {
                        try
                        {
                            foreach (object parameterObject in parameterObjects)
                            {
                                _dataMapper.Update(statementName, parameterObject);
                            }
                            transaction.Commit();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                        }
                        catch (Exception ex)
                        {
                            ErrorInfo = ex.Message;
                            transaction.Rollback();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                            return false;
                        }
                        finally
                        {
                            transaction.Complete();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                        }
                    }
                }
            }
            else
            {
                foreach (object parameterObject in parameterObjects)
                {
                    _dataMapper.Update(statementName, parameterObject);
                }
            }

            return true;

        }

        /// 
        /// 
        /// 
        ///
        ///
        ///
        /// 
        public bool Delete(string statementName, T parameterObject, out object returnValue)
        {
            if (IsAutoCommit)
            {
                using (ISession session = _sessionFactory.OpenSession())
                {
                    using (ITransaction transaction = session.BeginTransaction())
                    {
                        try
                        {
                            returnValue = _dataMapper.Delete(statementName, parameterObject);
                            transaction.Commit();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                        }
                        catch (Exception ex)
                        {
                            ErrorInfo = ex.Message;
                            transaction.Rollback();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                            returnValue = null;
                            return false;
                        }
                        finally
                        {
                            transaction.Complete();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                        }
                    }
                }
            }
            else
            {
                returnValue = _dataMapper.Delete(statementName, parameterObject);
            }
            return true;
        }
        /// 
        /// 
        /// 
        ///
        ///
        /// 
        public bool Delete(string statementName, IEnumerable parameterObjects)
        {
            if (IsAutoCommit)
            {
                using (ISession session = _sessionFactory.OpenSession())
                {
                    using (ITransaction transaction = session.BeginTransaction())
                    {
                        try
                        {
                            foreach (object parameterObject in parameterObjects)
                            {
                                _dataMapper.Delete(statementName, parameterObject);
                            }
                            transaction.Commit();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                            //return true;
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            ErrorInfo = ex.Message;
                            transaction.Rollback();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                            return false;
                        }
                        finally
                        {
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                        }
                    }

                }
                //  CommitTransaction();
            }
            else
            {
                foreach (object parameterObject in parameterObjects)
                {
                    _dataMapper.Delete(statementName, parameterObject);
                }
            }
            return true;
        }

        #region 实现对IList到DataSet的转换
        ///
        /// 实现对IList到DataSet的转换
        /// 
        ///待转换的IList
        /// 转换后的DataSet
        public DataSet ListToDataSet(IList resList)
        {
            var rds = new DataSet();
            //将DateTable放入DataSet
            rds.Tables.Add(ListToDataTable(resList));
            //返回DataSet
            return rds;
        }
        /// 
        /// 
        /// 
        ///
        /// 
        public DataTable ListToDataTable(IList resList)
        {
            var tempDt = new DataTable();

            //此处遍历IList的结构并建立同样的DataTable
            System.Reflection.PropertyInfo[] p = resList[0].GetType().GetProperties();
            foreach (System.Reflection.PropertyInfo pi in p)
            {
                Type colType = pi.PropertyType;
                if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                {
                    colType = colType.GetGenericArguments()[0];
                }
                // ReSharper disable once AssignNullToNotNullAttribute
                tempDt.Columns.Add(pi.Name, Type.GetType(colType.ToString()));
            }

            for (int i = 0; i < resList.Count; i++)
            {
                IList tempList = new ArrayList();
                //将IList中的一条记录写入ArrayList
                foreach (System.Reflection.PropertyInfo pi in p)
                {
                    object oo = pi.GetValue(resList[i], null);
                    tempList.Add(oo);
                }

                object[] itm = new object[p.Length];
                //遍历ArrayList向object[]里放数据
                for (int j = 0; j < tempList.Count; j++)
                {
                    itm.SetValue(tempList[j], j);
                }
                //将object[]的内容放入DataTable
                tempDt.LoadDataRow(itm, true);
            }

            return tempDt;
        }
        #endregion

        private Boolean _autoCommit = true;
        /// 
        /// 是否自动事物处理
        /// 
        public bool IsAutoCommit
        {
            get
            {
                return _autoCommit;
            }
            set
            {
                _autoCommit = value;
            }
        }
        /// 
        ///批量执行一组操作
        /// 
        ///
        /// 
        public int ExecutionBatch(List listParameter)
        {
            if (listParameter == null || listParameter.Count == 0)
            {
                return 1;
            }
            try
            {
                listParameter.Sort(delegate(MyBatisNetParameter a, MyBatisNetParameter b)
                {
                    return a.ExecSort.CompareTo(b.ExecSort);
                }
                );

                IsAutoCommit = false;
                bool succeed = true;
                using (ISession session = _sessionFactory.OpenSession())
                {
                    using (ITransaction transaction = session.BeginTransaction())
                    {
                        try
                        {
                            foreach (var item in listParameter)
                            {
                                if (item.ParemeterObject == null)
                                {
                                    continue;
                                }
                                if (item.StatementName == null || item.StatementName.Trim().Length <= 0)
                                {
                                    continue;
                                }
                                switch (item.ExecDbtype)
                                {
                                    case EnumExecDbType.Insert:
                                        succeed = item.ParemeterObject == null
                                            ? Insert(item.StatementName, item.ParemeterObject)
                                            : Insert(item.StatementName, item.ParemeterObject.ToArray());
                                        break;
                                    case EnumExecDbType.Update:
                                        succeed = item.ParemeterObject == null
                                            ? Update(item.StatementName, item.ParemeterObject)
                                            : Update(item.StatementName, item.ParemeterObject.ToArray());
                                        break;
                                    case EnumExecDbType.Delete:
                                        succeed = item.ParemeterObject == null
                                            ? Delete(item.StatementName, item.ParemeterObject)
                                            : Delete(item.StatementName, item.ParemeterObject.ToArray());

                                        break;
                                }
                                if (!succeed)
                                {
                                    transaction.Rollback();
                                    transaction.Dispose();
                                    if (session.Connection != null)
                                    {
                                        session.Connection.Close();
                                        session.Connection.Dispose();
                                    }
                                    session.Close();
                                    session.Dispose();
                                    return -1;
                                }
                            }
                            transaction.Commit();
                            transaction.Dispose();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                            IsAutoCommit = true;
                            // return 1;
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            ErrorInfo = ex.Message;
                            transaction.Dispose();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                            return -1;
                        }
                        finally
                        {
                            transaction.Complete();
                            transaction.Dispose();
                            if (session.Connection != null)
                            {
                                session.Connection.Close();
                                session.Connection.Dispose();
                            }
                            session.Close();
                            session.Dispose();
                            IsAutoCommit = true;
                        }
                    }

                }
                IsAutoCommit = true;
                return 1;

            }
            catch (Exception ex)
            {
                ErrorInfo = ex.Message;
                IsAutoCommit = true;
                if (ex.InnerException != null)
                {
                    throw new Exception(ex.Message, ex.InnerException);
                }
                return -1;
            }
            finally
            {
                IsAutoCommit = true;
            }
        }
        #region 取出错信息
        /// 
        /// 取出错信息
        /// 
        /// 
        public string GetErrText()
        {
            return ErrorInfo;
        }
        #endregion

        /// 
        ///深层复制一个实例
        /// 
        /// 
        public object Clone()
        {
            return new DatabaseMyBatis
            {
                DataMapper = DataMapper,
                ConnectionString = ConnectionString,
                ErrorInfo = ErrorInfo,
                IsAutoCommit = IsAutoCommit,
                Sequences = Sequences,
                //  SqlMapperForSequence = SqlMapperForSequence
            };
        }
        private bool _isDisposed;
        /// 
        /// 
        /// 
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        /// 
        /// 
        /// 
        ///
        protected virtual void Dispose(bool disposing)
        {
            if (!_isDisposed)
            {
                if (disposing)
                {
                    if (_session != null)
                    {
                        if (_session.Connection != null)
                        {
                            _session.Connection.Close();
                            _session.Connection.Dispose();
                        }
                        _session.Dispose();
                        _session = null;
                    }
                    //if (_sessionFactory != null)
                    //{
                    //    _sessionFactory.Dispose();
                    //    _sessionFactory = null;
                    //}
                    if (_transaction != null)
                    {
                        _transaction.Dispose();
                        _transaction = null;
                    }

                    //通过调用托管对象的Dispose()方法释放托管对象
                }
                CloseSession();
                //释放未托管对象的代码
                //比如关闭数据库的连接,关闭文件句柄等
            }
            _isDisposed = true;
        }
        /// 
        /// 
        /// 
        ~DatabaseMyBatis()
        {
            Dispose(false);
        }

    }


}
相关TAG标签
上一篇:iBATIS.NET 持久性框架解析
下一篇:c#窗体欢迎界面代码实现
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站