首页 > 解决方案 > Java Spring,如何检索记录并使用新的唯一键发布重复项?

问题描述

我想检索现有记录并使用新 ID 保留它的副本。当我尝试此操作时,我收到一条错误消息:“实例的标识符.....已从 1 更改为空”

这有点像我如何编码的一般总结。我将 newEntity ID 设置为 null 认为我的序列生成器将自动生成一个 ID。

Entity newEntity = repo.findById(id);
Entity newEntity.setId(null);
repo.save(newEntity);

标签: javaspring-boothibernatejpa

解决方案


您当前的方式不起作用,因为实体仍与会话相关联,因此您对该实体所做的任何更新都将保留在该实体本身中。您可以使用 BeanUtils 类的 copyProperties 方法,如下所示,这样新实体将是新的分离实体。

org.springframework.beans.BeanUtils.copyProperties(对象源,对象目标)

Entity existingEntity = repo.findById(id);
Entity newEntity = new Entity();
BeanUtils.copyProperties(existingEntity,newEntity);
newEntity.setId(null);
repo.save(newEntity);

推荐阅读