Where should "@Transactional" be place Service Layer or DAO

Shahzeb picture Shahzeb · Oct 8, 2010 · Viewed 45.1k times · Source

Firstly it is possible that I am asking something that has been asked and answered before but I could not get a search result back . Okay generally (or always so far:) ) We define transactional annotations on service layer typical spring hibernate crud is usually

Controller->Manager->Dao->Orm .

I now have a situation where I need to choose between the domain model based on client site . Say client A is using my domain model all is good but then an other client site would give me a web service and not be using our domain model .

Which layer should I be replacing . I believe it has to be DAO which will be getting me data from web service and sending it back.i.e two separately written DAO layers and plugged in based on scenario .

I have now realized that we have been doing tight coupling (if there is such a thing or say not having loose coupling) when we put @Transactional in Service layer . So many brains can not be wrong or are they (I doubt it).

So question is "Where should "@Transactional" be place Service Layer or DAO ?" and is it service layer downwards I should be replacing .

Answer

Badal picture Badal · Feb 26, 2015

Ideally, Service layer (Manager) represents your business logic and hence it should be annotated with @Transactional.

Service layer may call different DAOs to perform DB operations. Lets assume a situation where you have 3 DAO operations in a service method. If your 1st DAO operation failed, other two may be still passed and you will end up with an inconsistent DB state. Annotating Service layer can save you from such situations.