Please note that I have a look at How do I update an entity using spring-data-jpa?, but there is not a proper answer related to my question.
I am new in Spring Data JPA
and try to create a single proper method for both create and update operation. I am trying the following approach:
@Transactional
public CommandDTO createOrUpdate(EmployeeRequest request) {
Employee employee = employeeRepository
.findById(request.getId());
.orElse(new Employee());
employee.setName(request.getName());
// set other properties
final Employee saved = employeeRepository.save(employee);
return CommandDTO.builder().uuid((saved.getUuid())).build();
}
In this approach, I wanted to first try to find the record by Id and if not found create a new instance of it (for this reason I do not use Optional<Employee>
as it always returns a value). After that, I am looking for a method that look at the Primary Key parameter and if it is present, updates the record. If not create the a new record with the given parameters.
So, how should I complete the method? Or should I follow another approach in order to apply one of the best practices for Spring Data JPA
?