Jpa entity same record duplicated and making unique key violation

733 views Asked by At

I am using Jpa, my website is shows a form in 3 steps, in every step i'm making save() in many steps :

  • First save() will create a record A with a primary key id and another unique key userId, data as firstname and lastname
  • Step 2 is where the user will enter his adress, then the same first save() is played

But I see an error :

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

A save() is supposed to make an update if the record exists, but I noted that my id increments in every save() how to prevent this incrementation ?

here is my entity :

@Table(name = "user", schema = "salesforce", uniqueConstraints = {
    @UniqueConstraint(columnNames = { "userId" }) })

public class Beneficiary implements Serializable {

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;

The service :

void save(List<User> users, String idDocument); // it can be same users with same idDocument
public Beneficiary save(Beneficiary newBeneficiary);

The repository

@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);
    });
}

In every step, the same save() is played but first i got the error saying that I'm trying to write a new ligne with the same UserId and it creates the duplication violation

This re-write is due to the fact that Id is incrementing ! why ?

0

There are 0 answers