0

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!

elvis
  • 956
  • 9
  • 33
  • 56
  • 5
    Just add Unique Constraint for email in database and prepare for exception ConstraintViolationException or DataIntegrityViolationException. https://stackoverflow.com/a/3126800/516167 – MariuszS Aug 17 '20 at 15:12
  • 1
    Please read: [Can I ask only one question per post?](https://meta.stackexchange.com/questions/222735/can-i-ask-only-one-question-per-post) – Turing85 Aug 17 '20 at 15:14
  • 1
    Based on your attempt to define "the concurrency problem", it seems that the answer is "use transactions". – chrylis -cautiouslyoptimistic- Aug 17 '20 at 15:44
  • @chrylis What do you want to say with "use transactions"? Do I need to add Transactional annotation? So if I use Transactional is like I put synchronized at this method? – elvis Aug 17 '20 at 18:34
  • Using `@Transactional` is one way of setting up transactions (and the one I most commonly use). Transaction management is complicated and much less simple than `synchronized`; normally, multiple transactions run simultaneously (but you get varying levels of guarantees). – chrylis -cautiouslyoptimistic- Aug 17 '20 at 18:45

0 Answers0