Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring save only if doesn't exist

I want to save data only if doesn't exist, but not byID but byName for example.

Saving data for me working, but don't want duplicate.

    @RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveEmployee(@ModelAttribute("employee") Employee std) {
    Employee employee = new Employee();
    myRepoository.save(myRepoository.save(std)
   myRepoository.findById(employee.getId()).orElse(myRepoository.save(std)); //doesn't work
    return "redirect:/";
}
like image 762
Michal Hodul Avatar asked May 08 '26 09:05

Michal Hodul


1 Answers

You may first query the database by name something like:

List<Employees> findByName(String empName);

then if it does not find any name in the table the list stays empty. Now you have to check if the list size is zero save the data otherwise escape something like:

List<Employees> emps = repo.findByName("Mike");
if(!emps.size()>0){
//save the data
}

the code is not a working code just trying to give u an idea.

like image 78
Rafa Avatar answered May 09 '26 23:05

Rafa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!