码迷,mamicode.com
首页 > Web开发 > 详细

MyBatisNet数据操作类

时间:2017-10-31 21:25:53      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:exce   dict   tor   operation   处理   错误   one   action   ber   

 

 

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
{
    /// <summary>
    /// MyBatisNet数据操作类
    /// </summary>
    public class DatabaseMyBatis : IDatabaseMyBatis, IDisposable
    {

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

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

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="connectionString"></param>
        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");


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

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="sqlMapFileName"></param>
        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

        /// <summary>
        /// 连接到数据,并作相应的初始化
        /// </summary>
        /// <returns></returns>
        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;
            }

        }
        /// <summary>
        /// 连接到数据库,并作相应的初始化
        /// </summary>
        /// <returns></returns>
        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;
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public IDataMapper GetMapper()
        {
            return _dataMapper;
        }

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

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

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

        }
        #endregion
        #endregion
        /// <summary>
        /// 
        /// </summary>
        /// <param name="statementName"></param>
        /// <param name="parameterObject"></param>
        /// <returns></returns>
        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();
                    }
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="statementName"></param>
        /// <param name="parameterObject"></param>
        /// <returns></returns>
        public IList<T> QueryForList<T>(string statementName, object parameterObject)
        {
            using (var session = _sessionFactory.OpenSession())
            {
                using (var con = session.OpenConnection())
                {
                    try
                    {
                        var list = _dataMapper.QueryForList<T>(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();
                    }
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="statementName"></param>
        /// <param name="parameterObject"></param>
        /// <returns></returns>
        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();
                    }
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="statementName"></param>
        /// <param name="parameterObject"></param>
        /// <returns></returns>
        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();
                    }
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="statementName"></param>
        /// <param name="parameterObject"></param>
        /// <returns></returns>
        public T QueryForObject<T>(string statementName, object parameterObject)
        {
            using (var session = _sessionFactory.OpenSession())
            {
                using (var con = session.OpenConnection())
                {
                    try
                    {
                        var obj = _dataMapper.QueryForObject<T>(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();
                    }
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="statementName"></param>
        /// <param name="parameterObject"></param>
        /// <returns></returns>
        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;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <param name="statementName"></param>
        /// <param name="parameterObject"></param>
        /// <returns></returns>
        public Boolean QueryForDataTable<T>(out DataTable dt, string statementName, object parameterObject)
        {
            dt = new DataTable();
            try
            {
                // dt = new DataTable();
                IList<T> list = QueryForList<T>(statementName, parameterObject);
                T t1;
                if (list.Count <= 0)
                {
                    //dt = getDataTableForClass(typeof(T).ToString());
                    dt = GetDataTableForClass<T>();
                    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<T>();
                //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;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public DataTable GetDataTableForClass<T>()
        {
            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;

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="parameterClass"></param>
        /// <returns></returns>
        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;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="statementName"></param>
        /// <param name="parameterObject"></param>
        /// <param name="keyValue"></param>
        /// <param name="returnValue"></param>
        /// <returns></returns>
        public bool Insert<T>(string statementName, T parameterObject, ref Nullable<Int32> 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;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="statementName"></param>
        /// <param name="parameterObject"></param>
        /// <param name="returnValue"></param>
        /// <returns></returns>
        public bool Insert<T>(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;

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="statementName"></param>
        /// <param name="parameterObjects"></param>
        /// <returns></returns>
        public bool Insert<T>(string statementName, IEnumerable<T> 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;

        }

        /// <summary>
        /// 更新单条数据
        /// </summary>
        /// <param name="statementName"></param>
        /// <param name="parameterObject"></param>
        /// <param name="returnValue"></param>
        /// <returns></returns>
        public bool Update<T>(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;
        }
        /// <summary>
        /// 更新一组数据
        /// </summary>
        /// <param name="statementName"></param>
        /// <param name="parameterObjects"></param>
        /// <returns></returns>
        public bool Update<T>(string statementName, IEnumerable<T> 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;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="statementName"></param>
        /// <param name="parameterObject"></param>
        /// <param name="returnValue"></param>
        /// <returns></returns>
        public bool Delete<T>(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;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="statementName"></param>
        /// <param name="parameterObjects"></param>
        /// <returns></returns>
        public bool Delete<T>(string statementName, IEnumerable<T> 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的转换
        ///<summary>
        /// 实现对IList到DataSet的转换
        /// </summary>
        /// <param name="resList">待转换的IList</param>
        /// <returns>转换后的DataSet</returns>
        public DataSet ListToDataSet(IList resList)
        {
            var rds = new DataSet();
            //将DateTable放入DataSet
            rds.Tables.Add(ListToDataTable(resList));
            //返回DataSet
            return rds;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="resList"></param>
        /// <returns></returns>
        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;
        /// <summary>
        /// 是否自动事物处理
        /// </summary>
        public bool IsAutoCommit
        {
            get
            {
                return _autoCommit;
            }
            set
            {
                _autoCommit = value;
            }
        }
        /// <summary>
        ///批量执行一组操作
        /// </summary>
        /// <param name="listParameter"></param>
        /// <returns></returns>
        public int ExecutionBatch(List<MyBatisNetParameter> 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 取出错信息
        /// <summary>
        /// 取出错信息
        /// </summary>
        /// <returns></returns>
        public string GetErrText()
        {
            return ErrorInfo;
        }
        #endregion

        /// <summary>
        ///深层复制一个实例
        /// </summary>
        /// <returns></returns>
        public object Clone()
        {
            return new DatabaseMyBatis
            {
                DataMapper = DataMapper,
                ConnectionString = ConnectionString,
                ErrorInfo = ErrorInfo,
                IsAutoCommit = IsAutoCommit,
                Sequences = Sequences,
                //  SqlMapperForSequence = SqlMapperForSequence
            };
        }
        private bool _isDisposed;
        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="disposing"></param>
        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;
        }
        /// <summary>
        /// 
        /// </summary>
        ~DatabaseMyBatis()
        {
            Dispose(false);
        }

    }


}

 

MyBatisNet数据操作类

标签:exce   dict   tor   operation   处理   错误   one   action   ber   

原文地址:http://www.cnblogs.com/wangyinlon/p/7763518.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!