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 ?