0

How to check if a record exists in database before a save() because in my case, I have a field (not an @Id) that is a unique key. In my website, I have a form in 3 steps :

  • Step 1 : after setting firstname, lastname, the user clicks on "next" that will make a save() = Insert because the user is a new one in database. the is a column in database called "FirstnameAndLastname" which is the unique key
  • Step 2 : the user is asked to fill his email, and click on "next" : it's the same first save() and here is the error saying that a unique constraints violation happends !

And I understand it, as from step 1, the unique key is set, and in step 2 I try to write again with the same unique, so how to make the seconde save() to be an update ??

here is my entity :

@Entity
@Table(name = "student")
public class Student implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;

@Column(name = "firstname")
private String firstname;

 @Column(name = "lastname")
private String lastname;

@Column(name = "firstAndLastname")
private String firstLastname;

 // other columns + setter and getters etc

And here is my save()

@Override
public Student save(Student newStudent) {
    return studentRepository.save(newStudent);

}

@Override
@Transactional
public void save(List<Student> students, String firstname, String lastname) {
    students.forEach(newStudent-> {
        newStudent.setFirstLastname(firstname+lastname); // concatenation to make the unique key
        save(newStudent);
    });
}

I saw many answers saying that we should first fetch (find) student before saving, how to make it ?

Sushi
  • 646
  • 1
  • 13
  • 31
  • have your database auto increment your id's – Stultuske Apr 19 '21 at 09:23
  • @Stultuske Yes indeed, i forgot to copy/past this part, i'm editing my post – Sushi Apr 19 '21 at 09:24
  • 1
    the unique key is made of firstname and lastname, the id I was speaking about is not the @id on the entity, but let's say that the unique key is just firstname+lastname – Sushi Apr 19 '21 at 09:29
  • 1
    maybe this is helpful, https://stackoverflow.com/questions/11881479/how-do-i-update-an-entity-using-spring-data-jpa – Emerson Micu Apr 19 '21 at 09:38

0 Answers0