Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280177

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.

Upvotes: 13

Views: 19158

Answers (2)

michaelgulak
michaelgulak

Reputation: 631

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.

Upvotes: 3

kwh
kwh

Reputation: 664

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");
}

Upvotes: 7

Related Questions