Announcement Announcement Module
Collapse
No announcement yet.
Could not open Hibernate Session for transaction; nested exception is NPE Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Could not open Hibernate Session for transaction; nested exception is NPE

    After migrating to Hibernate 4 and Spring 3.1 RC2: I getting following exception and I have no idea why:

    Exception:

    Code:
        org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is java.lang.NullPointerException
        org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:428)
        ...
    Logging:

    Code:
     DEBUG Using SessionFactory 'sessionFactory' for OpenSessionInViewFilter
     DEBUG Opening Hibernate Session in OpenSessionInViewFilter
     DEBUG Found thread-bound Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])] for Hibernate transaction
     DEBUG Creating new transaction with name [com.project.server.dao.hibernate.BalanceDAOHibernateImpl.getCurrentBalance]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
     DEBUG txObject.getSessionHolder().getSession(: SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])
     DEBUG Preparing JDBC Connection of Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])]
     DEBUG SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])
     DEBUG Exposing Hibernate transaction as JDBC transaction [[email protected]620a822[valid=true]]
     DEBUG user: AbstractUser{id=30060, email='[email protected]', enabled=true}
     DEBUG ~~~~~~~~~~~~~~~~SESSION: SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])
     DEBUG ~~~~~~~~~~~~~~~~SESSION HOLDER session: SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])
     DEBUG BuyLaterQitem getByQitem createQuery list size: 1
     DEBUG user: AbstractUser{id=30060, email='[email protected]', enabled=true}
     DEBUG ~~~~~~~~~~~~~~~~SESSION: SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])
     DEBUG ~~~~~~~~~~~~~~~~SESSION HOLDER session: SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])
     DEBUG Initiating transaction commit
     DEBUG Committing Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])]
     DEBUG Not closing pre-bound Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])] after transaction
     DEBUG Found thread-bound Session [null] for Hibernate transaction
     DEBUG Creating new transaction with name [com.project.server.dao.hibernate.BalanceDAOHibernateImpl.getCurrentBalance]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
     DEBUG txObject.getSessionHolder().getSession(: null
     DEBUG Preparing JDBC Connection of Hibernate Session [null]
     DEBUG 
     DERROR java.lang.NullPointerException
    	at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:330)
     DEBUG Closing Hibernate Session in OpenSessionInViewFilter
    Application context:

    Code:
           
     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
                <property name="driverClass" value="${jdbc.driverClass}"/>
                <property name="jdbcUrl" value="${jdbc.url}"/>
                <property name="user" value="${env.jdbc.user}"/>
                <property name="password" value="${env.jdbc.password}"/>
                <property name="testConnectionOnCheckin" value="true"/>
                <property name="testConnectionOnCheckout" value="true"/>
            </bean>
                <bean class="org.springframework.orm.hibernate4.HibernateExceptionTranslator"/>
                <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
                <property name="dataSource" ref="dataSource"/>
                    <property name="packagesToScan">
                    <list>
                        <value>com.project.server.dao.hibernate</value>
                        <value>com.project.server.service.impl</value>
                        <value>com.project.server.service.handler</value>
                        <value>com.project.server.service.schedule</value>
                        <value>com.project.server.service.gateway.impl</value>
                    </list>
                </property>
                    <property name="mappingResources">
                    <list>
                        <value>com/project/server/domain/AdminApplication.hbm.xml</value>
                        ...   
                    </list>
                </property>
                <property name="hibernateProperties">
                    <props>
                        <prop key="hibernate.dialect">${db.dialect}</prop>
                        <prop key="hibernate.show_sql">false</prop>
                        <prop key="hibernate.format_sql">false</prop>
                        <prop key="hibernate.use_sql_comments">false</prop>
                        <prop key="hibernate.max_fetch_depth">1</prop>
                        <prop key="hibernate.cache.use_structured_entries">false</prop>
                        <prop key="hibernate.bytecode.use_reflection_optimizer">false</prop>
                        <prop key="hibernate.jdbc.batch_size">100</prop>
                        <prop key="hibernate.generate_statistics">false</prop>
                        <prop key="hibernate.cache.use_query_cache">true</prop>
                        <prop key="hibernate.cache.use_second_level_cache">true</prop>
                        <prop key="hibernate.cache.use_minimal_puts">true</prop>
                        <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</prop>
                        <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
    
                            <!--hibernate search -->
                        <prop key="hibernate.search.default.directory_provider">org.hibernate.search.store.impl.FSDirectoryProvider</prop>
                        <prop key="hibernate.search.default.indexBase">${server.compass.repo}</prop>
                        <prop key="hibernate.search.default.batch.merge_factor">3</prop>
                        <prop key="hibernate.search.id.new_generator_mappings">true</prop>
                        <prop key="hibernate.search.default.optimizer.operation_limit.max">1000</prop>
                        <prop key="hibernate.search.default.optimizer.transaction_limit.max">100</prop>
                        <prop key="hibernate.search.reader.strategy">not-shared</prop>
                        <prop key="hibernate.search.worker.execution">async</prop>
                        <prop key="hibernate.search.worker.thread_pool.size">20</prop>
                        <prop key="hibernate.search.worker.buffer_queue.max">100</prop>
                            <prop key="max_fetch_depth">1</prop>
            
                    </props>
                </property>
            </bean>
                <tx:annotation-driven/>
                <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
                <property name="sessionFactory" ref="sessionFactory"/>
               <!-- <property name="hibernateManagedSession" value="false"/> -->
                </bean>
                <tx:advice id="txAdvice" transaction-manager="txManager">
                <tx:attributes>
                    <tx:method name="get*" read-only="true"/>
                    <tx:method name="*"/>
                </tx:attributes>
            </tx:advice>
                <aop:config>
                <aop:pointcut id="loadableActionOperation" expression="execution(* com.project.server.domain.LoadableAction.*(..))"/>
                <aop:advisor advice-ref="txAdvice" pointcut-ref="loadableActionOperation"/>
            </aop:config>

    After little source code digging it seems that this the NullPointer Culprit (line# 342):
    Code:
    org.springframework.orm.hibernate4.HibernateTransactionManager (@author Juergen Hoeller) :
    
              session = txObject.getSessionHolder().getSession();
    
    337     if (this.prepareConnection && isSameConnectionForEntireSession(session)) {
    		// We're allowed to change the transaction settings of the JDBC Connection.
    		if (logger.isDebugEnabled()) {
    		logger.debug("Preparing JDBC Connection of Hibernate Session [" + session + "]");
    		}
    342     Connection con = ((SessionImplementor) session).connection();
    	  Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
    	  txObject.setPreviousIsolationLevel(previousIsolationLevel);
    345	  }
    Can someone explain to me why
    txObject.getSessionHolder().getSession();
    would return null even though the session seems to exist according to the log?
    Last edited by momatej; Dec 11th, 2011, 08:50 PM.

  • #2
    Hi, we have the similar problem in our new application.

    After debugging our app on Hibernate 4 and then on Hibernate 3 I found the cause of this problem. After completition of each transaction HibernateTransactionManager calls:

    Code:
    txObject.getSessionHolder().clear();
    in method doCleanupAfterCompletion.

    But in new implementation of SessionHolder (org.springframework.orm.hibernate4.SessionHolder) clear method looks like this:

    Code:
    public void clear() {
         super.clear();
         this.session = null;
         this.transaction = null;
         this.previousFlushMode = null;
    }
    and clears the session with null. In old Hibernate3 implementation session wasn't cleaned. So if we have more then one transaction in one request, we got this exception.

    We fixed this with not clearing the session in clear method od SessionHolder but we don't know if this clearing was there for some purpose or if it was by accident.

    Thanks for reply!

    Comment

    Working...
    X