0

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 ?

Sushi
  • 646
  • 1
  • 13
  • 31
  • I think, you are trying to save the detached User object, hibernate will try to save object, it is not aware that there is already a object with same `id`, hence it will issue the insert statement with `id`, you need to first fetch the object and then make changes to that. – code_mechanic Apr 14 '21 at 16:10
  • Yes indeed @code_mechanic it means the fetch should be done before the save in my repository ? findAllById ? – Sushi Apr 14 '21 at 16:57
  • Yes, but fetch by Id each user and then update its state with the properties of your detached object, updates are little hard with JPA. – code_mechanic Apr 14 '21 at 17:08
  • `EntityManager.merge` makes it easy but sometimes thats not the option. – code_mechanic Apr 14 '21 at 17:11
  • Although, you should fetch first and then update but your problem is different, you have constraint on `userId`, so please check if that value is not repeating for every user, if you are adding new user using `save` method every time then your code is fine. – code_mechanic Apr 14 '21 at 17:35

0 Answers0