[使用Hibernate备份和恢复数据库

问题描述 投票:0回答:1

我希望可以通过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(以保持实体之间的链接),但是休眠状态不允许我这样做。

感谢您的回答。

java database hibernate java-ee database-backups
1个回答
0
投票

看起来像另一个在当前提交之前在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);
© www.soinside.com 2019 - 2024. All rights reserved.