If i have Spring data repository which includes save, delete and modify operations. Should I create the following methods operations in service layer? And adding annotation @Transactional
?
Or leave them as is? Or should I have them in repository layer?
Example service
@Service
public class RepositoryOperations{
@Autowired
ProductRepository productRepository;
@Transactional
public void saveProduct(){
productRepository.save();
}
...
}
I think that you are using a good approach for your code. You can create a service layer that will invoke the product repository methods in order to separate responsibilities (business from data logic).
A 3-layered architecture describes your approach as follows:
In order to prevent any inconsistent in your saveProduct() service method when a problem occurs, you can use the @Transactional annotation in order to rollback all the changes made by your method in the database, so i consider it's a good practice use that annotation when you are working with writing operations in database.
We keep three layers generally.
Annotate your dao layer with annotation @Repository
Annotate your service layer with annotation @Service
Annotate your controllers with annotation @Controller
or @RestController(in case you have REST APIs)
@Transactional
annotation is used when you want a code to be rolled back if it fails. If your service places three dao calls for three different operations and you want all or none of those three operations to be performed, annotate your service method with @Transactional
Same applies for dao methods.
So you have now fair amount of information to decide upon.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With