Transaction management across multiple DAOs in spring

February 6th, 2009 | Tags: , ,

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.

  1. prashant shelke
    March 13th, 2009 at 09:55
    Reply | Quote | #1

    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. December 2nd, 2009 at 03:26
    Reply | Quote | #2

    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!

  3. December 10th, 2009 at 06:11
    Reply | Quote | #3

    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

  4. doit
    December 16th, 2009 at 20:43
    Reply | Quote | #4

    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