Back Forum Reply New

Cannot catch Rollback Exceptions with @Transactional

Hi,

I cant seem to find an elegant solution to this problem. I have a Service Layer which callls my DAO Layer. My business methods in my Service layer are annotated with @Transactional.

Simple Service method:

Code:
class EmployeeService {    @Transactional    public void savePerson(Person person) {        try {  personDAO.saveNewPerson(person);        } catch(Exception e) {  System.out.println(quot;ERROR: quot; + e.getMessage);  //However any rollback exception does not get caught here at all        }    }

}

Now if there is some constraint violation on saving this Person object then this will not be caught by the catch all Exception in the service method. The problem is @Transactional makes a AOP proxy out of this service and so the transaction is not committed until the method exits. Therefore the exception is thrown within the proxy where it commits and so it is too late for me to catch it.

I have read through the forums and done the @Repository annotation in my DAO. Some suggest flushing the entity just before the method exits but I have no reference to the persistent context in my Service layer and only use @PersistentContext in my DAO's for the persistent context to be injected via Spring. Hence I cannot flush in my service.

So what is the elegant solution to this problem where you want to use the @Transactional to mark transactions in your Service methods and want to catch exceptions from the database that will only be thrown when the transaction commits which occurs when the methods exits?

The only solution I could think to solve this problem is to have a Facade in my Service Layer which is used by the client but then delegates the calls to my @Transactional marked methods. e.g.EmployeeServiceFacade:

Code:

class EmployeeServiceFacade {    EmployeeService emp;
    void savePerson(Person person) {          try {emp.savePerson(person);          } catch(Exception e) {   //Now the exception after transaction commit would get caught here   System.out.println(quot;ERROR: quot; + e.getMessage());          }    }

}

However this does not seem an elegant solution. Can anyone suggest anything better?Thanks
ASC
¥
Back Forum Reply New