Search in sources :

Example 11 with DataAccessException

use of org.springframework.dao.DataAccessException in project spring-framework by spring-projects.

the class AbstractJdbcInsert method executeInsertAndReturnKeyHolderInternal.

/**
	 * Delegate method to execute the insert, generating any number of keys.
	 */
private KeyHolder executeInsertAndReturnKeyHolderInternal(final List<?> values) {
    if (logger.isDebugEnabled()) {
        logger.debug("The following parameters are used for call " + getInsertString() + " with: " + values);
    }
    final KeyHolder keyHolder = new GeneratedKeyHolder();
    if (this.tableMetaDataContext.isGetGeneratedKeysSupported()) {
        getJdbcTemplate().update(new PreparedStatementCreator() {

            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement ps = prepareStatementForGeneratedKeys(con);
                setParameterValues(ps, values, getInsertTypes());
                return ps;
            }
        }, keyHolder);
    } else {
        if (!this.tableMetaDataContext.isGetGeneratedKeysSimulated()) {
            throw new InvalidDataAccessResourceUsageException("The getGeneratedKeys feature is not supported by this database");
        }
        if (getGeneratedKeyNames().length < 1) {
            throw new InvalidDataAccessApiUsageException("Generated Key Name(s) not specified. " + "Using the generated keys features requires specifying the name(s) of the generated column(s)");
        }
        if (getGeneratedKeyNames().length > 1) {
            throw new InvalidDataAccessApiUsageException("Current database only supports retrieving the key for a single column. There are " + getGeneratedKeyNames().length + " columns specified: " + Arrays.asList(getGeneratedKeyNames()));
        }
        // This is a hack to be able to get the generated key from a database that doesn't support
        // get generated keys feature. HSQL is one, PostgreSQL is another. Postgres uses a RETURNING
        // clause while HSQL uses a second query that has to be executed with the same connection.
        final String keyQuery = this.tableMetaDataContext.getSimulationQueryForGetGeneratedKey(this.tableMetaDataContext.getTableName(), getGeneratedKeyNames()[0]);
        Assert.notNull(keyQuery, "Query for simulating get generated keys can't be null");
        if (keyQuery.toUpperCase().startsWith("RETURNING")) {
            Long key = getJdbcTemplate().queryForObject(getInsertString() + " " + keyQuery, values.toArray(new Object[values.size()]), Long.class);
            Map<String, Object> keys = new HashMap<>(1);
            keys.put(getGeneratedKeyNames()[0], key);
            keyHolder.getKeyList().add(keys);
        } else {
            getJdbcTemplate().execute(new ConnectionCallback<Object>() {

                @Override
                public Object doInConnection(Connection con) throws SQLException, DataAccessException {
                    // Do the insert
                    PreparedStatement ps = null;
                    try {
                        ps = con.prepareStatement(getInsertString());
                        setParameterValues(ps, values, getInsertTypes());
                        ps.executeUpdate();
                    } finally {
                        JdbcUtils.closeStatement(ps);
                    }
                    //Get the key
                    Statement keyStmt = null;
                    ResultSet rs = null;
                    Map<String, Object> keys = new HashMap<>(1);
                    try {
                        keyStmt = con.createStatement();
                        rs = keyStmt.executeQuery(keyQuery);
                        if (rs.next()) {
                            long key = rs.getLong(1);
                            keys.put(getGeneratedKeyNames()[0], key);
                            keyHolder.getKeyList().add(keys);
                        }
                    } finally {
                        JdbcUtils.closeResultSet(rs);
                        JdbcUtils.closeStatement(keyStmt);
                    }
                    return null;
                }
            });
        }
        return keyHolder;
    }
    return keyHolder;
}
Also used : SQLException(java.sql.SQLException) HashMap(java.util.HashMap) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) KeyHolder(org.springframework.jdbc.support.KeyHolder) GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException) PreparedStatementCreator(org.springframework.jdbc.core.PreparedStatementCreator) ResultSet(java.sql.ResultSet) InvalidDataAccessResourceUsageException(org.springframework.dao.InvalidDataAccessResourceUsageException) HashMap(java.util.HashMap) Map(java.util.Map) DataAccessException(org.springframework.dao.DataAccessException)

Example 12 with DataAccessException

use of org.springframework.dao.DataAccessException in project spring-framework by spring-projects.

the class SQLErrorCodeSQLExceptionTranslatorTests method errorCodeTranslation.

@Test
public void errorCodeTranslation() {
    SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);
    SQLException badSqlEx = new SQLException("", "", 1);
    BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", badSqlEx);
    assertEquals("SQL", bsgex.getSql());
    assertEquals(badSqlEx, bsgex.getSQLException());
    SQLException invResEx = new SQLException("", "", 4);
    InvalidResultSetAccessException irsex = (InvalidResultSetAccessException) sext.translate("task", "SQL", invResEx);
    assertEquals("SQL", irsex.getSql());
    assertEquals(invResEx, irsex.getSQLException());
    checkTranslation(sext, 5, DataAccessResourceFailureException.class);
    checkTranslation(sext, 6, DataIntegrityViolationException.class);
    checkTranslation(sext, 7, CannotAcquireLockException.class);
    checkTranslation(sext, 8, DeadlockLoserDataAccessException.class);
    checkTranslation(sext, 9, CannotSerializeTransactionException.class);
    checkTranslation(sext, 10, DuplicateKeyException.class);
    SQLException dupKeyEx = new SQLException("", "", 10);
    DataAccessException dksex = sext.translate("task", "SQL", dupKeyEx);
    assertTrue("Not instance of DataIntegrityViolationException", DataIntegrityViolationException.class.isAssignableFrom(dksex.getClass()));
    // Test fallback. We assume that no database will ever return this error code,
    // but 07xxx will be bad grammar picked up by the fallback SQLState translator
    SQLException sex = new SQLException("", "07xxx", 666666666);
    BadSqlGrammarException bsgex2 = (BadSqlGrammarException) sext.translate("task", "SQL2", sex);
    assertEquals("SQL2", bsgex2.getSql());
    assertEquals(sex, bsgex2.getSQLException());
}
Also used : BadSqlGrammarException(org.springframework.jdbc.BadSqlGrammarException) SQLException(java.sql.SQLException) InvalidResultSetAccessException(org.springframework.jdbc.InvalidResultSetAccessException) DataAccessException(org.springframework.dao.DataAccessException) DeadlockLoserDataAccessException(org.springframework.dao.DeadlockLoserDataAccessException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) Test(org.junit.Test)

Example 13 with DataAccessException

use of org.springframework.dao.DataAccessException in project spring-framework by spring-projects.

the class SQLErrorCodeSQLExceptionTranslatorTests method customTranslateMethodTranslation.

@SuppressWarnings("serial")
@Test
public void customTranslateMethodTranslation() {
    final String TASK = "TASK";
    final String SQL = "SQL SELECT *";
    final DataAccessException customDex = new DataAccessException("") {
    };
    final SQLException badSqlEx = new SQLException("", "", 1);
    SQLException intVioEx = new SQLException("", "", 6);
    SQLErrorCodeSQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator() {

        @Override
        protected DataAccessException customTranslate(String task, String sql, SQLException sqlex) {
            assertEquals(TASK, task);
            assertEquals(SQL, sql);
            return (sqlex == badSqlEx) ? customDex : null;
        }
    };
    sext.setSqlErrorCodes(ERROR_CODES);
    // Shouldn't custom translate this
    assertEquals(customDex, sext.translate(TASK, SQL, badSqlEx));
    DataIntegrityViolationException diex = (DataIntegrityViolationException) sext.translate(TASK, SQL, intVioEx);
    assertEquals(intVioEx, diex.getCause());
}
Also used : SQLException(java.sql.SQLException) DataAccessException(org.springframework.dao.DataAccessException) DeadlockLoserDataAccessException(org.springframework.dao.DeadlockLoserDataAccessException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) Test(org.junit.Test)

Example 14 with DataAccessException

use of org.springframework.dao.DataAccessException in project spring-framework by spring-projects.

the class SQLErrorCodeSQLExceptionTranslatorTests method checkTranslation.

private void checkTranslation(SQLExceptionTranslator sext, int errorCode, Class<?> exClass) {
    SQLException sex = new SQLException("", "", errorCode);
    DataAccessException ex = sext.translate("", "", sex);
    assertTrue(exClass.isInstance(ex));
    assertTrue(ex.getCause() == sex);
}
Also used : SQLException(java.sql.SQLException) DataAccessException(org.springframework.dao.DataAccessException) DeadlockLoserDataAccessException(org.springframework.dao.DeadlockLoserDataAccessException)

Example 15 with DataAccessException

use of org.springframework.dao.DataAccessException in project spring-framework by spring-projects.

the class SQLExceptionCustomTranslatorTests method dataAccessResourceException.

@Test
public void dataAccessResourceException() {
    SQLException dataAccessResourceEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 2);
    DataAccessException dae = sext.translate("task", "SQL", dataAccessResourceEx);
    assertEquals(dataAccessResourceEx, dae.getCause());
    assertThat(dae, instanceOf(TransientDataAccessResourceException.class));
}
Also used : TransientDataAccessResourceException(org.springframework.dao.TransientDataAccessResourceException) SQLException(java.sql.SQLException) DataAccessException(org.springframework.dao.DataAccessException) Test(org.junit.Test)

Aggregations

DataAccessException (org.springframework.dao.DataAccessException)73 SQLException (java.sql.SQLException)40 Test (org.junit.Test)20 Connection (java.sql.Connection)17 ResultSet (java.sql.ResultSet)16 PreparedStatement (java.sql.PreparedStatement)14 TransactionStatus (org.springframework.transaction.TransactionStatus)7 HashMap (java.util.HashMap)6 DeadlockLoserDataAccessException (org.springframework.dao.DeadlockLoserDataAccessException)5 IncorrectResultSizeDataAccessException (org.springframework.dao.IncorrectResultSizeDataAccessException)5 IOException (java.io.IOException)4 EmptyResultDataAccessException (org.springframework.dao.EmptyResultDataAccessException)4 ConnectionCallback (org.springframework.jdbc.core.ConnectionCallback)4 SpringSqlParams (com.opengamma.elsql.SpringSqlParams)3 DatabaseMetaData (java.sql.DatabaseMetaData)3 Statement (java.sql.Statement)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 IJoinQueryString (org.apereo.portal.jdbc.IJoinQueryString)3 DataIntegrityViolationException (org.springframework.dao.DataIntegrityViolationException)3