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.
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