Transaction management across multiple DAOs in spring

A question commonly asked on the spring forums is that a service makes calls to multiple DAOs, how can ALL the calls be rolledback if any of the calls throws an exception. The simplest way to do this is to make your service transactional while keeping your DAOs non-transactional.
Example Service :

//imports & package
@Service
@Transactional
public class UserServiceImpl implements UserService {

	@Override
        public void addUser(User user) {
		userDao.doFirstOperation();
		userDao.doSecondOperation();
	}
}

Notice the lack of @Transactional annotation in the DAO below.

public class UserDao {
	public void doFirstOperation() {
		// some stuff
	}

	public void doSecondOperation() {
		// some stuff
	}
}

Remember that your DAO methods MUST through an unchecked or runtime exception for the transaction to rollback on its own. Otherwise you have to declare the rollback in case of a checked exception.

Share and Enjoy:
  • del.icio.us
  • Google Bookmarks
  • DZone
  • Reddit
  • Digg
  • Facebook
  • Netvibes
  • StumbleUpon
  • Technorati
  • LinkedIn
  • MySpace
  • Print
  • Slashdot
  • Share/Bookmark

No related posts.

Tags: , ,

5 Responses to “Transaction management across multiple DAOs in spring”

  1. prashant shelke says:

    In case of mine,
    Service –> DAOImpl methods i am calling. I am using Spring JDBC transactions management by application context
    see: http://forum.springframework.org/showthread.php?t=68751

    How I can make DAO calling from Service layer non-transactional ?

  2. [...] all my webapps mainly because it keeps the code clean and also because it makes it much easier to manage transactions across DAO’s. My cache was placed in the service layer and was implemented something like this [...]

  3. Andy says:

    I’m thinking our brains work very similarly and we are not in the majority. If the Spring documentation had this article alone, 90% of people would understand how transactions and rollbacks work as well as how they should most likely be designed. Nice job!

  4. satya says:

    I am doing the exact thing like you mentioned in your article. But some reason my Annotation based transactions are not working. Could you please please provide your working sample or some instructions on configuring the annotations in xml

  5. doit says:

    Hi,

    can anybody guide me in the below concern.

    I have two services and two dao’s

    Test1Service,Test1Dao
    Test2Service, Test2Dao.

    Test1Dao updates test1 table
    Test2Dao updates test2 table.

    now in a particular call i need to update test1 and test2 tables from Test1Service

    please help me in this regard on how to configure and workout

Leave a Reply