我試圖使用hibernate寫入多個數(shù)據(jù)庫.我在單個會話對象中封裝了寫入和讀取/寫入會話.但是,當(dāng)我去保存時,我收到很多錯誤,表明對象已經(jīng)與另一個會話相關(guān)聯(lián):“非法嘗試將集合與兩個打開的會話相關(guān)聯(lián)”
這是我的代碼:
public class MultiSessionObject implements Session {
private Session writeOnlySession;
private Session readWriteSession;
@Override
public void saveOrUpdate(Object arg0) throws HibernateException {
readWriteSession.saveOrUpdate(arg0);
writeOnlySession.saveOrUpdate(arg0);
}
}
我試過驅(qū)逐物體并沖洗;但是,這會導(dǎo)致“Row被另一個事務(wù)更新或刪除”的問題……即使兩個會話都指向不同的數(shù)據(jù)庫.
public class MultiSessionObject implements Session {
private Session writeOnlySession;
private Session readWriteSession;
@Override
public void saveOrUpdate(Object arg0) throws HibernateException {
readWriteSession.saveOrUpdate(arg0);
readWriteSession.flush();
readWriteSession.evict(arg0);
writeOnlySession.saveOrUpdate(arg0);
writeOnlySession.flush();
writeOnlySession.evict(arg0);
}
}
除了上述內(nèi)容之外,我還嘗試使用hibernate的復(fù)制功能.這也沒有成功,沒有錯誤.
有沒有人成功將對象保存到兩個具有相同模式的數(shù)據(jù)庫中? 解決方法: saveOrUpdate嘗試將給定的Entity重新附加到當(dāng)前運(yùn)行的Session,因此Proxies(LAZY association)綁定到Hibernate Session.嘗試使用merge instead of saveOrUpdate,因?yàn)閙erge只是將分離的實(shí)體狀態(tài)復(fù)制到新檢索的托管實(shí)體.這樣,提供的參數(shù)永遠(yuǎn)不會附加到Session.
另一個問題是交易管理.如果您使用線程綁定事務(wù),那么如果要從同一個線程更新兩個DataSource,則需要兩個顯式事務(wù).
嘗試也明確設(shè)置事務(wù)邊界:
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;
}
}
}
來源:https://www./content-1-485451.html
|