I am learning Spring-MVC in my first project here.
After reading the documentation on transactions I noted that all of the examples put transactions around the service objects/methods, not the DAO (data access objects/methods).
I wondered why. Without knowing better I would think to add transactions around most of my DAO methods that access the database (my thinking: database=transactions). I don't yet have many service methods that span multiple DAO's (but I guess that could be a reason for marking services as transactional).
The question:
I just want to know what others do in this situation. Do you naturally put transactions around the lowest level item that you can (e.g. around DAOs always, and around services only when they span multiple DAO's in a way which requires transactions)?
Or do you just focus on transactions around services as a general principal? Thus sticking to one layer because that's more all-encompassing in the long run?
You should use @Transactional at service layer, if you want to change the domain model for client B where you have to provide the same data in a different model,you can change the domain model without impacting the DAO layer by providing a different service or by creating a interface and implementing the interface in ...
Transactions indeed put locks on the database — good database engines handle concurrent locks in a sensible way — and are useful with read-only use to ensure that no other transaction adds data that makes your view inconsistent.
The @Transactional annotation makes use of the attributes rollbackFor or rollbackForClassName to rollback the transactions, and the attributes noRollbackFor or noRollbackForClassName to avoid rollback on listed exceptions. The default rollback behavior in the declarative approach will rollback on runtime exceptions.
I USE THE @Transactional in @Controller and Just make a Generic Save Method and save all the entities/ model using this simple save method. and if any method fail to save then all the transactions in controller rollback successfully.
For my money I try the put the transaction at the coarsest point possible in the app, this tends to be a service/manager like object that coordinates calls to one or more finer gained dao calls.
In theory you could put transactions everywhere from services to daos, assuming they are defined to join an existing transaction if required. In practice I've found this less than useful as it is unnecessary and will just annoy you when attempting to debug the code.
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