Massimo Ugues
Massimo Ugues

Reputation: 4463

Spring translate java.sql.SQLException to DataAccessException

Hallo. Since it seems that I cannot use the spring DataAccessException translation mechanism in my dao, I would like to know if it possible to translate the

Internal Exception: java.sql.SQLException: [BEA][Oracle JDBC Driver][Oracle]ORA-00001: unique constraint (JSP_OWN.IDX_MC_CC_RAPPORTI_02) violated

to the DataAccessException hierarchy manually.

Kind regards Massimo

Upvotes: 1

Views: 3519

Answers (1)

xmedeko
xmedeko

Reputation: 7805

If you have a JdbcTemplate, you can do

catch (SqlException e) {
  throw jdbcTemplate.getExceptionTranslator().translate("my task", null, e);
}

If you do not have JdbcTemplate, just look at the source code of the JdbcTemplate.getExceptionTranslator() method:

public synchronized SQLExceptionTranslator getExceptionTranslator() {
    if (this.exceptionTranslator == null) {
        DataSource dataSource = getDataSource();
        if (dataSource != null) {
            this.exceptionTranslator = new SQLErrorCodeSQLExceptionTranslator(dataSource);
        }
        else {
            this.exceptionTranslator = new SQLStateSQLExceptionTranslator();
        }
    }
    return this.exceptionTranslator;
}

And mimic it's behaviour :-)

Upvotes: 1

Related Questions