Reputation: 280177
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
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
Reputation: 664
Spring provides Exception Handlers.
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