Search code examples
javaspringhibernatetransactionsrollback

Manage rollback on transaction in my managed bean


I am using JPA/hibernate, Spring and JSF.
so my application is organized as following:
I have my entities,
My Dao Interface and implementation for each entity where I define basic methods: findById, add, update, remove ... and then I have my service layer which just use DAO interfaces and where ther is basically the same methods as in my DAO.
My problem is that in my backing bean, I have a method Add_hospital(), which add a hospital and also services in that hospital, so my method looks like

add_hospital(){ 
add-hospital(); 
add-services();
add-Hospital-schedule();
}

so this method is a transaction and I want that if some issue happen, the transaction rollback, but I know that the rollback need to be managed in my DAO, will I need to define my method Add_hospital() in my managed bean, and it's in this stage where I have this combination of inserts.
Please how to solve this problem?


Solution

  • Transactions should be managed on the service layer, not data access. Example from spring:

    @Transactional(readOnly = true)
    public class DefaultFooService implements FooService {
    
        public Foo getFoo(String fooName) {
            // do something
        }
    
        // these settings have precedence for this method
        @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
        public void updateFoo(Foo foo) {
            // do something
        }
    }