Michal Hodul
Michal Hodul

Reputation: 91

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:/";
}

Upvotes: 4

Views: 3539

Answers (1)

Rafa
Rafa

Reputation: 487

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.

Upvotes: 1

Related Questions