在
saveOrUpdate尝试重新连接一个给定的实体运行会话的电流,所以代理(懒惰协会)绑定到Hibernate的Session。尝试使用merge而不是saveOrUpdate,因为
merge只需将分离的实体状态复制到新检索的受管实体。这样,提供的参数永远不会附加到会话。
另一个问题是事务管理。如果使用线程绑定事务,则要从同一线程更新两个数据源,则需要两个显式事务。
也尝试显式设置事务边界:
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; } }}


