We open transactions only in read mode, and then convert them to write mode, since read-only connections will not be a problem, as this is using a database.
We override the HibernateTemplate class and create methods to execute the session in write mode
public final void writeEnabled(){ getSession().doWork(jdbcWorkWriteEnabled); } public final void writeDisabled(boolean flush){ if(flush) flush(); getSession().doWork(jdbcWorkWriteDisabled); } public static final void writeEnabled(Session session){ session.doWork(jdbcWorkWriteEnabled); } public static final void writeDisabled(boolean flush,Session session){ if(flush) session.flush(); session.doWork(jdbcWorkWriteDisabled); } final static Work jdbcWorkWriteEnabled = new Work(){ public void execute(Connection connection) throws SQLException { connection.setReadOnly(false); } }; final static Work jdbcWorkWriteDisabled = new Work(){ public void execute(Connection connection) throws SQLException { connection.setReadOnly(true); } };
In the application logic, before recording, we check the connection is in recording mode, and then just write.
otherwise, if the connection is read-only, first make it in write mode, perform a write operation, and return it to its original state again.
source share