Posts Tagged ‘transaction management’

Transaction management across multiple DAOs in spring

Friday, February 6th, 2009

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.