David Parks
David Parks

Reputation: 32091

Spring-MVC best practices: Why put transactions on services rather than DAOs?

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?

Upvotes: 7

Views: 2122

Answers (3)

James Kingsbery
James Kingsbery

Reputation: 7496

The other answers are right, but to add color to the answers: the transaction goes at the service layer should encapsulate an atomic piece of business logic. Since this business logic should stand alone without interference from other business logic, the transactions need to be at the service layer.

Upvotes: 0

Gareth Davis
Gareth Davis

Reputation: 28069

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.

Upvotes: 4

Faisal Feroz
Faisal Feroz

Reputation: 12785

This is done so that the data that you have selected/queried from the DataSource remains valid while you are processing on the data.

In other case (putting transactions on DAO) the data can be changed while you are processing on the data and might get wrong results.

Upvotes: 2

Related Questions