how to convert a read only hibernate session to write during a transaction (Master/Slave DB)

冷暖自知 提交于 2019-12-25 08:21:24

问题


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

The transactions that are opened are in read-only mode i.e pointing to slave DB. What is the best way to convert it to write mode if I want to save/update/delete any thing during that transaction?

I do not want to open a write mode transaction as most of the time I want read stuff.

Do I need to overide the replication Driver/Hibernate template for this thing?


回答1:


We open transactions in read only mode and then convert it to write mode as read only connections will not be an issue as it is with salve DB.

We override the HibernateTemplate class and create methods to make 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 application logic before write we check
Connection is in write mode then simply write.
else if connection is readonly then first make it in write mode, do write operation and again make it back to readonly



来源:https://stackoverflow.com/questions/8694254/how-to-convert-a-read-only-hibernate-session-to-write-during-a-transaction-mast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!