Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception Handling with Spring's @Transactional

I'm developing a web app with Spring MVC and hibernate for persistence. Given my DAO where GenericDao has a SessionFactory member attribute:

@Repository
public class Dao extends GenericDao {
    public void save(Object o) {
        getCurrentSession().save(o);
    }
}

And a Service class

@Service
public class MyService {
    @Autowired
    Dao dao;

    @Transactional
    public void save(Object o) {
        dao.save(o);
    }
}

I want to inform my user if a persistence exception occurs (constraint, duplicate, etc). As far as I know, the @Transactional annotation only works if the exception bubbles up and the transaction manager rolls back so I shouldn't be handling the exception in that method. Where and how should I catch an exception that would've happened in the DAO so that I can present it to my user, either directly or wrapped in my own exception?

I want to use spring's transaction support.

like image 950
Sotirios Delimanolis Avatar asked Dec 07 '12 15:12

Sotirios Delimanolis


2 Answers

Spring provides Exception Handlers.

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-exceptionhandlers

So you could have something like this in your controller to handle a ConstraintViolationException

  @ExceptionHandler(ConstraintViolationException.class)
  public ModelAndView handleConstraintViolationException(IOException ex, Command command, HttpServletRequest request) 
{
    return new ModelAndView("ConstraintViolationExceptionView");
}
like image 165
kwh Avatar answered Sep 18 '22 18:09

kwh


After chasing around the issue for a while, I solved this by using an exception handler (as described in another answer) and the rollbackFor property of the @Transactional annotation:

@Transactional(rollbackFor = Exception.class)

My exception handler is still called and writes the response accordingly, but the transaction is rolled back.

like image 26
michaelgulak Avatar answered Sep 18 '22 18:09

michaelgulak