使用Hibernate备份和恢复数据库



我希望能够通过Hibernate备份和恢复数据库。

流程是:

1( 将每个表中的所有实体获取到HashMap,并将整个映射序列化到文件中。

2( 从数据库中清除所有实体。

3( 反序列化文件并将所有实体持久化回数据库。

在步骤3中,我面对的是:

javax.persistence.OptimisticLockException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [*.*.entities.User#1]

这种情况发生在以下代码中:

session.saveOrUpdate(entity);
session.getTransaction().commit(); // <- here

我的所有实体都扩展了BasicEntity,它只有这个ID定义:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

我做错了什么?我想,我不能保存实体(从文件恢复(,它有一些ID,但我需要这样做并保存当前ID(以保持实体之间的链接(,但hibernate不允许我这样做。

谢谢你的回答。

看起来像是在当前提交之前在db中更新的另一个线程。尝试以下选项之一

//check if it's in the cache, if it's then refresh and then saveorupdate
if (session.contains(entity) session.refresh(entity);
saveOrUpdate(entity);
//Load the object from the database and then update
dbEntity= session.load(classname.class, 2);
saveOrUpdate(dbEntity);

最新更新