How to convert a read-only hibernation session to write during a transaction (Master / Slave DB)

Working with MySql replication using spring + hibernate, I have a quick question;

Open transactions are in read-only mode, indicating a slave database. What is the best way to convert it to recording mode if I want to save / update / delete any thing during this transaction?

I do not want to open a write mode transaction, because most of the time I want to read material.

Do I need to override the driver / hibernate pattern for this thing?

0
source share
1 answer

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.

+1
source

Source: https://habr.com/ru/post/1415351/


All Articles