private void DoClose(bool isLogDebugEnabled)
 {
     if (!IsParticipating)
     {
         if (SingleSession)
         {
             // single session mode
             if (isLogDebugEnabled)
             {
                 log.Debug("Closing single Hibernate Session in SessionScope");
             }
             LazySessionHolder holder = (LazySessionHolder)TransactionSynchronizationManager.UnbindResource(SessionFactory);
             holder.Close();
         }
         else
         {
             // deferred close mode
             if (isLogDebugEnabled)
             {
                 log.Debug("Closing all Hibernate Sessions");
             }
             SessionFactoryUtils.ProcessDeferredClose(SessionFactory);
         }
     }
     else
     {
         if (isLogDebugEnabled)
         {
             log.Debug("Only participated Hibernate Session - doing nothing");
         }
     }
 }
        private ISession DoOpenSession()
        {
            ISession session = SessionFactoryUtils.OpenSession(SessionFactory, EntityInterceptor);

            session.FlushMode = DefaultFlushMode;
            return(session);
        }
 private void CloseConversation(IConversationState conversation)
 {
     if (log.IsDebugEnabled)
     {
         log.Debug(String.Format("CloseConversation: Id='{0}'", conversation.Id));
     }
     if (conversation.RootSessionPerConversation != null)
     {
         ISession tmpSession = conversation.RootSessionPerConversation;
         if (conversation.Ended)
         {
             SessionFactoryUtils.CloseSession(tmpSession);
             conversation.RootSessionPerConversation = null;
         }
         else
         {
             if (tmpSession.IsConnected)
             {
                 tmpSession.Disconnect();
             }
         }
         RemoveSession(tmpSession);
     }
     if (log.IsDebugEnabled)
     {
         log.Debug("Closed LazySessionPerConversationHolder");
     }
 }
示例#4
0
            private void CloseConversation(IConversationState conversation)
            {
                if (log.IsDebugEnabled)
                {
                    log.Debug($"CloseConversation: Id='{conversation.Id}'");
                }

                if (conversation.RootSessionPerConversation != null)
                {
                    ISession tmpSession = conversation.RootSessionPerConversation;
                    if (conversation.Ended)
                    {
                        SessionFactoryUtils.CloseSession(tmpSession);
                        conversation.RootSessionPerConversation = null;
                    }
                    else
                    {
                        if (tmpSession.IsConnected)
                        {
                            IDbConnection conn = tmpSession.Disconnect();
                            if (conn != null && conn.State == ConnectionState.Open)
                            {
                                conn.Close();
                            }
                        }
                    }
                    RemoveSession(tmpSession);
                }
                if (log.IsDebugEnabled)
                {
                    log.Debug("Closed LazySessionPerConversationHolder");
                }
            }
        public static IDbProvider GetDbProvider(ISessionFactory sessionFactory)
        {
            //ISessionFactoryImplementor sfi = sessionFactory as ISessionFactoryImplementor;
            //if (sfi != null)
            //{
            //    Spring.Data.NHibernate.LocalSessionFactoryObject.DbProviderWrapper p = sfi.ConnectionProvider as Spring.Data.NHibernate.LocalSessionFactoryObject.DbProviderWrapper;
            //    if (p != null)
            //        return p.DbProvider;

            //}
            //return null;
            //修改获取DbProvider的方法
            IDbProvider provider = SessionFactoryUtils.GetDbProvider(sessionFactory);

            if (provider == null)
            {
                ISessionFactoryImplementor sfi = sessionFactory as ISessionFactoryImplementor;
                if (sfi != null)
                {
                    Spring.Data.NHibernate.LocalSessionFactoryObject.DbProviderWrapper p = sfi.ConnectionProvider as Spring.Data.NHibernate.LocalSessionFactoryObject.DbProviderWrapper;
                    if (p != null)
                    {
                        return(p.DbProvider);
                    }
                }
            }
            return(provider);
        }
示例#6
0
 /// <summary>
 /// Get a Hibernate Session, either from the current transaction or
 /// a new one. The latter is only allowed if "allowCreate" is true.
 /// </summary>
 /// <remarks>Note that this is not meant to be invoked from HibernateTemplate code
 /// but rather just in plain Hibernate code. Either rely on a thread-bound
 /// Session (via HibernateInterceptor), or use it in combination with
 /// ReleaseSession.
 /// <para>
 /// In general, it is recommended to use HibernateTemplate, either with
 /// the provided convenience operations or with a custom HibernateCallback
 /// that provides you with a Session to work on. HibernateTemplate will care
 /// for all resource management and for proper exception conversion.
 /// </para>
 /// </remarks>
 /// <param name="allowCreate"> if a non-transactional Session should be created when no
 /// transactional Session can be found for the current thread
 /// </param>
 /// <returns>Hibernate session.</returns>
 /// <exception cref="DataAccessResourceFailureException">
 /// If the Session couldn't be created
 /// </exception>
 /// <exception cref="InvalidOperationException">
 /// if no thread-bound Session found and allowCreate false
 /// </exception>
 /// <seealso cref="ReleaseSession"/>
 protected ISession DoGetSession(bool allowCreate)
 {
     return(!allowCreate ?
            SessionFactoryUtils.GetSession(SessionFactory, false) :
            SessionFactoryUtils.GetSession(
                SessionFactory,
                this.hibernateTemplate.EntityInterceptor,
                this.hibernateTemplate.AdoExceptionTranslator));
 }
        /// <summary>
        /// Opens a new session or participates in an existing session and
        /// registers with spring's <see cref="TransactionSynchronizationManager"/>.
        /// </summary>
        public void Open()
        {
            if (IsParticipating || IsOpen)
            {
                throw new InvalidOperationException("This scope is already open");
            }

            bool isDebugEnabled = log.IsDebugEnabled;

            if (SingleSession)
            {
                // single session mode
                if (TransactionSynchronizationManager.HasResource(SessionFactory))
                {
                    // Do not modify the Session: just set the participate flag.
                    if (isDebugEnabled)
                    {
                        log.Debug("Participating in existing Hibernate SessionFactory");
                    }
                    SetParticipating(true);
                }
                else
                {
                    if (isDebugEnabled)
                    {
                        log.Debug("Opening single Hibernate Session in SessionScope");
                    }
                    TransactionSynchronizationManager.BindResource(SessionFactory, new LazySessionHolder(this));
                }
            }
            else
            {
                // deferred close mode
                if (SessionFactoryUtils.IsDeferredCloseActive(SessionFactory))
                {
                    // Do not modify deferred close: just set the participate flag.
                    if (isDebugEnabled)
                    {
                        log.Debug("Participating in active deferred close mode");
                    }
                    SetParticipating(true);
                }
                else
                {
                    if (isDebugEnabled)
                    {
                        log.Debug("Initializing deferred close mode");
                    }
                    SessionFactoryUtils.InitDeferredClose(SessionFactory);
                }
            }

            SetOpen(true);
        }
示例#8
0
        public void CustomerDaoTests()
        {
            Assert.AreEqual(91, customerDao.GetAll().Count);

            Customer c = new Customer(new DefaultCustomerClassificationCalculator());

            c.Id          = "MPOLL";
            c.CompanyName = "Interface21";
            customerDao.Save(c);
            c = customerDao.Get("MPOLL");
            Assert.AreEqual(c.Id, "MPOLL");
            Assert.AreEqual(c.CompanyName, "Interface21");

            //Without flushing, nothing changes in the database:
            int customerCount = (int)AdoTemplate.ExecuteScalar(CommandType.Text, "select count(*) from Customers");

            Assert.AreEqual(91, customerCount);

            //Flush the session to execute sql in the db.
            SessionFactoryUtils.GetSession(sessionFactory, true).Flush();

            //Now changes are visible outside the session but within the same database transaction
            customerCount = (int)AdoTemplate.ExecuteScalar(CommandType.Text, "select count(*) from Customers");
            Assert.AreEqual(92, customerCount);

            Assert.AreEqual(92, customerDao.GetAll().Count);

            c.CompanyName = "SpringSource";

            customerDao.Update(c);

            c = customerDao.Get("MPOLL");
            Assert.AreEqual(c.Id, "MPOLL");
            Assert.AreEqual(c.CompanyName, "SpringSource");

            customerDao.Delete(c);


            SessionFactoryUtils.GetSession(sessionFactory, true).Flush();
            customerCount = (int)AdoTemplate.ExecuteScalar(CommandType.Text, "select count(*) from Customers");
            Assert.AreEqual(92, customerCount);

            try
            {
                c = customerDao.Get("MPOLL");
                Assert.Fail("Should have thrown HibernateObjectRetrievalFailureException when finding customer with Id = MPOLL");
            }
            catch (HibernateObjectRetrievalFailureException e)
            {
                Assert.AreEqual("Customer", e.PersistentClassName);
            }
        }
示例#9
0
        public void ProductDaoTests()
        {
            Assert.AreEqual(830, orderDao.GetAll().Count);

            Order    order    = new Order();
            Customer customer = customerDao.Get("PICCO");

            order.Customer = customer;
            order.ShipCity = "New York";

            orderDao.Save(order);
            int orderId = order.Id;

            order = orderDao.Get(orderId);
            Assert.AreEqual("PICCO", order.Customer.Id);
            Assert.AreEqual("New York", order.ShipCity);

            //SessionFactoryUtils.GetSession(sessionFactory, true).Flush();
            // Required trip to db to get idendity column, so data is visible

            int ordersCount = (int)AdoTemplate.ExecuteScalar(CommandType.Text, "select count(*) from Orders");

            Assert.AreEqual(831, ordersCount);

            Assert.AreEqual(831, orderDao.GetAll().Count);

            order.ShipCity = "Sao Paulo";
            orderDao.Update(order);

            order = orderDao.Get(orderId);
            Assert.AreEqual("PICCO", order.Customer.Id);
            Assert.AreEqual("Sao Paulo", order.ShipCity);


            orderDao.Delete(order);

            //Without flushing, nothing changes in the database:
            SessionFactoryUtils.GetSession(sessionFactory, true).Flush();

            ordersCount = (int)AdoTemplate.ExecuteScalar(CommandType.Text, "select count(*) from Orders");
            Assert.AreEqual(830, ordersCount);

            try
            {
                order = orderDao.Get(orderId);
                Assert.Fail("Should have thrown HibernateObjectRetrievalFailureException when finding order with Id = " + orderId);
            }
            catch (HibernateObjectRetrievalFailureException e)
            {
                Assert.AreEqual("Order", e.PersistentClassName);
            }
        }
示例#10
0
        /// <summary>
        /// Creates new criteria object and applies the transaction timeout
        /// configured as part of the transaction attributes
        /// example: <tx:method name="Get*" read-only="true" timeout="900"/>
        /// </summary>
        /// <typeparam name="T">Type requesting the criteria</typeparam>
        /// <param name="session">NHibernate session</param>
        /// <returns></returns>
        private ICriteria GetCriteria <T>(ISession session)
        {
            ICriteria Criteria = session.CreateCriteria(typeof(T));

            SessionFactoryUtils.ApplyTransactionTimeout(Criteria, sessionFactory);

            NHibernate.Engine.ISessionFactoryImplementor sessionFactoryImpl = sessionFactory as NHibernate.Engine.ISessionFactoryImplementor;
            if (sessionFactoryImpl != null && sessionFactoryImpl.Settings.IsQueryCacheEnabled)
            {
                Criteria.SetCacheable(true);
            }
            return(Criteria);
        }
示例#11
0
 /// <summary>
 /// Ensure session is closed (if any) and remove circular references to avoid memory leaks!
 /// </summary>
 public void Close()
 {
     owner = null;
     if (session != null)
     {
         ISession tmpSession = session;
         session = null;
         SessionFactoryUtils.CloseSession(tmpSession);
     }
     if (log.IsDebugEnabled)
     {
         log.Debug("Closed LazySessionHolder");
     }
 }
示例#12
0
 /// <summary>
 /// Close the given Hibernate Session, created via this DAO's SessionFactory,
 /// if it isn't bound to the thread.
 /// </summary>
 /// <remarks>
 /// Typically used in plain Hibernate code, in combination with the
 /// Session property and ConvertHibernateAccessException.
 /// </remarks>
 /// <param name="session">The session to close.</param>
 protected void ReleaseSession(ISession session)
 {
     SessionFactoryUtils.ReleaseSession(session, SessionFactory);
 }
 private ISession GetSession()
 {
     return(SessionFactoryUtils.GetSession(sessionFactory, true));
 }
示例#14
0
 private void CloseSession(ISession session)
 {
     SessionFactoryUtils.CloseSession(session);
 }