首页 > 解决方案 > Jpa实体相同的记录重复并导致唯一密钥违规

问题描述

我正在使用 Jpa,我的网站分 3 个步骤显示表单,每一步我都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!为什么 ?

标签: javajpaentityconstraintviolationexception

解决方案


推荐阅读