Question

I have a service, which uses multiple DAOs to do a unit of work like following. The DAOs fetch the data/save by creating a session and commit. In that case, why do i need to have transactional on the service when the dao is managing the session by itself? If something goes wrong in the second DAO, the data in the first DAO is already commited, how do I get around this situation?

@Transactional
public boolean testService(SomeObject obj){

     userDao.save(obj.getUser()); // this dao gets the session from sessino factory and commits there itself.
     addressDao.save(obj.getAddress()); // something fails here, and the above line has already commited the data, so the data is not Atomic.

     return true;
}
Was it helpful?

Solution

Usually you don't put @Transactional in your DAO layer but in your service layer. So I suggest you remove @Transactional from you DAOs and keep the one in your service.

In that case, if something goes wrong in any of your DAO everything will be rollback.

But It's up to you where you want the transaction to start and to finish.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top