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

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.

Leave a Comment