如何在NHibernate中批量导入数据

运行环境:VS2008

1)使用IStatelessSession, 设置hibernate.cfg.xml中:<property name="adonet.batch_size">250</property>.

2) 如果不想忍受调试时导入的慢速度,设置<property name="show_sql">false</property>>(此配置用于调试时在控制台输出sql script,检查错误,但是会使导入变成龟速)。

3)代码如下:

     3.1)创建Session:

      public class Common

     {        

        /// <summary>
        /// Init a open  Stateless session, caller needs to close this session manually.
        /// <para>It used to commit a lot of data in a transaction</para>
        /// </summary>
        public static IStatelessSession StatelessSession
        {
            get
            {
                lock (thisLock)
                {
                    if (sessionFactory == null)
                    {
                        Configuration cfg = new Configuration();
                        sessionFactory = cfg.Configure().BuildSessionFactory();
                    }
                    IStatelessSession session = null;

                    try
                    {
                        session = sessionFactory.OpenStatelessSession();
                        return session;

                    }
                    catch
                    {
                        return null;
                    }
                }
            }
        }

 

        private static ISessionFactory sessionFactory;
        private static readonly object thisLock = new object();
      
    }

 

      }

   3.2) 批量保存:       

           

      public static bool save(List<object> objs, out string msg)
        {
            IStatelessSession session = Common.StatelessSession;
            bool _result = false;
            msg = "";
            if (session == null)
                return false;

            using (session)
            {
                using (ITransaction tran = session.BeginTransaction())
                {
                    try
                    {
                        foreach (var _item in objs)
                        {
                            session.Insert(_item);
                        }
                        tran.Commit();
                        _result = true;
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        msg = ex.Message + "--" + ex.InnerException;
                    }
                }
            }
            return _result;
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值