Java / Hibernate - Write operations are not allowed in read-only mode

后端 未结 11 2151
迷失自我
迷失自我 2020-11-28 11:18

I\'ve been having an annoying exception a lot lately, and after some research on Google and this forum I still haven\'t found an answer that could solve my problem.

相关标签:
11条回答
  • 2020-11-28 11:56

    add

    @Transactional
    

    above your function

    0 讨论(0)
  • 2020-11-28 11:59

    Use below bean for HibernateTemplate in application context.

    <bean id="template" class="org.springframework.orm.hibernate4.HibernateTemplate">  
            <property name="sessionFactory" ref="mysessionFactory"></property>
            <property name="checkWriteOperations" value="false"></property>
            </bean>
    
    0 讨论(0)
  • 2020-11-28 12:06

    That error message is typically seen when using the Spring OpenSessionInViewFilter and trying to do persistence operations outside of a Spring-managed transaction. The filter sets the session to FlushMode.NEVER/MANUAL (depending on the versions of Spring and Hibernate you're using--they're roughly equivalent). When the Spring transaction mechanism begins a transaction, it changes the flush mode to "COMMIT". After the transaction completes, it sets it back to NEVER/MANUAL, as appropriate. If you're absolutely sure that this isn't happening, then the next most likely culprit is non-thread-safe use of a Session. The Hibernate Session must be used in only one thread. If it crosses over between threads, all kinds of chaos can happen. Note that an entity loaded from Hibernate can hold a reference to the Session in which it was loaded, and handing the entity across threads can thus cause the Session to be accessed from another thread, too.

    0 讨论(0)
  • 2020-11-28 12:06

    I had the same problem and after one day of investigation I observed the following declaration

    <tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/>
    

    I removed

    mode="aspectj"
    

    and the problem disappeared

    0 讨论(0)
  • 2020-11-28 12:07

    Try to use this

    hibernateTemplate = new HibernateTemplate(sessionFactory);
    hibernateTemplate.setCheckWriteOperations(false);
    

    The error should go away as the template is not checking if you are using a transaction.

    0 讨论(0)
提交回复
热议问题