Jpa 实体相同记录重复并违反唯一键

问题描述

我正在使用 Jpa,我的网站分 3 个步骤显示一个表单,每一步我都在许多步骤中制作 save() :

  • 第一个 save() 将创建一条记录 A,其中包含一个主键 id 和另一个唯一键 userId,数据为名字和姓氏
  • 第 2 步是用户输入他的地址,然后播放相同的第一个 save()

但我看到一个错误:

ERROR: duplicate key value violates unique constraint "userId" XXXX already exists

如果记录存在,save() 应该生成 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 是递增的!为什么?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...