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

I just stumbled onto this too. I needed to change the flush mode in Spring's OpenSessionInViewFilter to manual, and suddenly I started getting this exception. I found out that the problems were happening in methods that were not annotated as @Transactional, so I guess that Spring implicitly treats all data access code outside such methods as read only. Annotating the method solved the problem.

Another way is to call the setCheckWriteOperations method on the HibernateTemplate object.


I changed the single session propery from view filter. Problem solved:

  <filter>
    <filter-name>hibernateFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
    <init-param>
      <param-name>singleSession</param-name>
      <param-value>false</param-value>
    </init-param>
  </filter>

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.


add

@Transactional

above your function