Write a Custom SQLExceptionTranslator
. This way you are going to be directly translating exceptions direct from the database. I'm not sure on the specifics but something like the following should be able to get you started:
public class CustomSQLExceptionTranslator implements SQLExceptionTranslator{
@Override
protected DataAccessException translate(String task, String sql, SQLException ex) {
switch(ex.getErrorCode()){
case(Primary Key Violation Error Code): {
return new PrimaryKeyViolationException(ex); //Or whatever exception you want.
}
...
default:{
return ex;
}
}
}
That way you can catch as many or as few exceptions as you like, and if you aren't wanting to throw a custom exception yourself, just return the exception as was given. Now you just have to work out how to add your CustomSQLExceptionTranslator
bean to the PersistenceExceptionTranslator
that is part of your session factory.
Please note, I haven't ever done this myself. This is just my best guess on how to proceed. I have no idea if this is standard industry practice or if there is a standard way to do this. I gladly yield to someone who has done this before.