Sunday, January 27, 2013

InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode

If you have enabled the filter OpenSessionInViewFilter, for fetching the lazily loaded data, you can typically see the below error message, when trying to do a persistence operation outside of Spring-managed transaction.

org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
org.springframework.orm.hibernate3.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1186)
org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:696)
org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:419)
org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:694)

OpenSessionInViewFilter has an alternative "deferred close mode", to resolve the issue. This can be activated through setting the singleSession=false. This will use one Session per transaction, but keep each of those open until view rendering has been completed. As no Session will be reused for another transaction in this case, there is no risk of accidentally flushing inconsistent state


  OpenSessionInViewFilter
  org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
  
     singleSession     false  


Happy Programming !!!