Hibernate Save Object to Multiple Sessions

前端 未结 3 1027
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 10:17

I am attempting to write to multiple databases using hibernate. I have encapsulated write and read/write sessions within a single session object. However, when I go to sav

3条回答
  •  独厮守ぢ
    2020-12-29 10:20

    The saveOrUpdate tries to reattach a given Entity to the current running Session, so Proxies (LAZY associations) are bound to the Hibernate Session. Try using merge instead of saveOrUpdate, because merge simply copies a detached entity state to a newly retrieved managed entity. This way, the supplied arguments never gets attached to a Session.

    Another problem is Transaction Management. If you use Thread-bound Transaction, then you need two explicit transactions if you want to update two DataSources from the same Thread.

    Try to set the transaction boundaries explicitly too:

    public class MultiSessionObject implements Session {
    
       private Session writeOnlySession;
       private Session readWriteSession;
    
       @Override
       public void saveOrUpdate(Object arg0) throws HibernateException {
    
            Transaction readWriteSessionTx = null;
            try {
                readWriteSessionTx = readWriteSession.beginTransaction();
                readWriteSession.merge(arg0);
                readWriteSessionTx.commit();
            } catch (RuntimeException e) {
                if ( readWriteSessionTx != null && readWriteSessionTx.isActive() ) 
                    readWriteSessionTx.rollback();
                throw e;
            }
    
            Transaction writeOnlySessionTx = null;
            try {
                writeOnlySessionTx = writeOnlySession.beginTransaction();
                writeOnlySession.merge(arg0);
                writeOnlySessionTx.commit();
            } catch (RuntimeException e) {
                if ( writeOnlySessionTx != null && writeOnlySessionTx.isActive() ) 
                    writeOnlySessionTx.rollback();
                throw e;
            }
       }
    }
    

提交回复
热议问题