I'm working at a simple Spring Boot project, and I want to create a resource in the database. So the client will send a POST request with a body that contains these information: name, age, email, password. The app has a RestController a Service and a DAO that communicate with the database using Spring Data JPA. I want to know how to resolve the concurrency problem for this POST request.
Controller:
@RestController
@RequestMapping(value = "/api/v1")
public class UserApi {
@Autowired
private UserService userService;
@PostMapping("/users")
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
}
Service interface:
public interface UserService {
User createUser(User user);
}
Service class:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public User createUser(User user) {
return userRepository.save(user);
}
}
DAO:
public interface UserRepository extends JpaRepository<User, Integer> {
}
So it is a simple POST request to create a user in the database. And I want to know how to resolve the concurrency problem. For example if 2 users call the createUser method in the same time and they have the same email address.
And the second question is why it is recommended to have an interface for service layer and then a class that implement this interface and to inject the interface into the constructor? I see this design on many projects. Why it isn't recommend to have just a class, without an interface and inject the class in the constructor?
Thank you in advance!