java - Java Spring,如何检索记录并使用新的唯一键发布重复项?
问题描述
我想检索现有记录并使用新 ID 保留它的副本。当我尝试此操作时,我收到一条错误消息:“实例的标识符.....已从 1 更改为空”
这有点像我如何编码的一般总结。我将 newEntity ID 设置为 null 认为我的序列生成器将自动生成一个 ID。
Entity newEntity = repo.findById(id);
Entity newEntity.setId(null);
repo.save(newEntity);
解决方案
您当前的方式不起作用,因为实体仍与会话相关联,因此您对该实体所做的任何更新都将保留在该实体本身中。您可以使用 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);
推荐阅读
- winapi - CCM_DPISCALE 通用控制消息
- excel - 带循环的单元格的相对参考
- python - async Python 真的是异步的吗?
- angular - 错误类型错误:“值未定义”角度 5 httpclient
- r - 如何使用 df2(t)/df2(t-1) 的比率轻松填写 df1(at time t) 的缺失值?
- android - 字符串在 Android 中总是返回 null
- android - 键盘弹出时按钮不向上滚动
- scala - 多个scala数据框concat
- pdf - 堆叠 PDF 图像:单页输出
- c# - 我正在尝试使用变量在 C# 中初始化 DateTime