我试图使用hibernate写入多个数据库.我在单个会话对象中封装了写入和读取/写入会话.但是,当我去保存时,我收到很多错误,表明对象已经与另一个会话相关联:“非法尝试将集合与两个打开的会话相关联”
这是我的代码:
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);
}
}
我试过驱逐物体并冲洗;但是,这会导致“Row被另一个事务更新或删除”的问题……即使两个会话都指向不同的数据库.
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);
}
}
除了上述内容之外,我还尝试使用hibernate的复制功能.这也没有成功,没有错误.
有没有人成功将对象保存到两个具有相同模式的数据库中? 解决方法: saveOrUpdate尝试将给定的Entity重新附加到当前运行的Session,因此Proxies(LAZY association)绑定到Hibernate Session.尝试使用merge instead of saveOrUpdate,因为merge只是将分离的实体状态复制到新检索的托管实体.这样,提供的参数永远不会附加到Session.
另一个问题是交易管理.如果您使用线程绑定事务,那么如果要从同一个线程更新两个DataSource,则需要两个显式事务.
尝试也明确设置事务边界:
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
|