I've made a system that use JPA and Spring. For example, If I need to handle Accounts, I use a repository:
@Repository
public interface AccountRepository extends JpaRepository<Account, Long>
Then I create a service that use the repository:
class AccountServiceImpl implements AccountService {
@Autowired
private AccountRepository repository;
@Transactional
public Account save(Account account){
return repository.save(account);
}
...
Now, I've created a controller that handle the POST method for Accounts:
@Controller
public class AccountController {
@Autowired
private final accountService service;
@RequestMapping(value = "/account", method = RequestMethod.POST)
public ModelAndView account(@Valid Account account, BindingResult bindingResult) {
...
service.save(account);
The same for Customer, Products, Contacts, etc.
Now, let suppose that I also have a class called "registration" that containts enough data to create a customer, with his accounts, contact data and products(a lot of data). The action "confirm" to a registration is the one dedicated to do that:
@RequestMapping(value = "/confirm", method = RequestMethod.POST)
public ModelAndView confirmRegistration(@Valid Registration registration, BindingResult bindingResult) {
Now my question: What is the correct way to call the save method for every repository?
1) Should I create the classes in the controller and then call the save method for every class created:
@RequestMapping(value = "/confirm", method = RequestMethod.POST)
public ModelAndView confirmRegistration(@Valid Registration registration, BindingResult bindingResult) {
...
customerService.save(customer);
accountService.save(account);
contactDataService.save(contactData);
productService.save(contactData);
...
2) Call the saves of each service in the RegistrationService:
class RegistrationServiceImpl implements RegistrationService {
@Autowired
private AccountService accountService;
@Autowired
private CustomerService customerService;
....
@Transactional
public void confirm(Registration registration){
... here I create the object
customerService.save(customer);
accountService.save(account);
}
3) Call the saves of each repository in the RegistrationService:
class RegistrationServiceImpl implements RegistrationService {
@Autowired
private AccountRepository accountRepository;
@Autowired
private CustomerRepository customerRepository;
....
@Transactional
public void confirm(Registration registration){
... here I create the object
customerRepository.save(customer);
accountRepository.save(account);
}
I undertand if I have to use (1). But confused about option (2) and (3).
The question again:
Should/Can I use other services in a service? Or I have to use only repositories in a service?
What is the correct way to google the explanation of this? Sorry English is not my native language and I can't find the correct way to ask about this kind of design.