java - Jpa实体相同的记录重复并导致唯一密钥违规
问题描述
我正在使用 Jpa,我的网站分 3 个步骤显示表单,每一步我都save()
在很多步骤中进行:
- First
save()
将创建一个A
具有主键id
和另一个唯一键的记录userId
,数据作为名字和姓氏 - 第 2 步是用户输入他的地址的地方,然后同样先
save()
播放
但我看到一个错误:
ERROR: duplicate key value violates unique constraint "userId" XXXX already exists
如果记录存在, Asave()
应该做一个update
,但我注意到我的id
增量是save()
如何防止这种增量的?
这是我的实体:
@Table(name = "user", schema = "salesforce", uniqueConstraints = {
@UniqueConstraint(columnNames = { "userId" }) })
公共类受益人实现可序列化{
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "userID")
private String userId;
@Column(name = "firstname")
private String firstname;
@Column(name = "lastname")
private String lastname;
服务 :
void save(List<User> users, String idDocument); // it can be same users with same idDocument
public Beneficiary save(Beneficiary newBeneficiary);
存储库
@Override
public User save(User newUser) {
return userRepository.save(newUser);
}
@Override
@Transactional
public void save(List<User> users, String idDocument) {
users.forEach(newUser -> {
newUser.setDocument(new Document());
newUser.getDocument().setIDDocument(idDocument);
save(newUser);
});
}
在每一步中,save()
都会播放相同的内容,但首先我收到错误消息,说我正在尝试使用相同的 UserId 编写一个新的 ligne,它会创建重复违规
这种重写是由于增加的事实Id
!为什么 ?
解决方案
推荐阅读
- gradle - kotlin multiplatform shadow fat jar 和 runShadow 任务?
- tinyos - 我们可以为 TinyOS 应用程序使用 COOJA 模拟器吗?
- html - 如何正确自定义 ul-li 标签创建的下拉菜单?
- ios - 处理格式和数据正确的音频文件时出错
- javascript - 如何使引导程序崩溃平滑
- python - 如果不调用函数是否可以引发异常
- ionic-framework - 将 Bootstrap 与 Stenciljs 一起使用
- nearprotocol - NFT 有价转账
- r - 如何删除R中的列?
- android - 如果可以的话,使用更具体的更改事件总是更有效。依靠 notifyDataSetChanged 作为最后的手段。回收视图