Example usage for org.springframework.jdbc UncategorizedSQLException getCause

List of usage examples for org.springframework.jdbc UncategorizedSQLException getCause

Introduction

In this page you can find the example usage for org.springframework.jdbc UncategorizedSQLException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:fi.luontola.cqrshotel.framework.PsqlEventStore.java

@Override
public long saveEvents(UUID streamId, List<Event> newEvents, int expectedVersion) {
    try (Connection connection = DataSourceUtils.getConnection(dataSource)) {
        Array data = connection.createArrayOf("jsonb", serializeData(newEvents));
        Array metadata = connection.createArrayOf("jsonb", serializeMetadata(newEvents));

        long endPosition = jdbcTemplate.queryForObject(
                "SELECT save_events(:stream_id, :expected_version, :data, :metadata)",
                new MapSqlParameterSource().addValue("stream_id", streamId)
                        .addValue("expected_version", expectedVersion).addValue("data", data)
                        .addValue("metadata", metadata),
                Long.class);

        if (log.isTraceEnabled()) {
            for (int i = 0; i < newEvents.size(); i++) {
                int newVersion = expectedVersion + 1 + i;
                Event newEvent = newEvents.get(i);
                log.trace("Saved stream {} version {}: {}", streamId, newVersion, newEvent);
            }//from ww w .ja va2 s . c o  m
        }
        return endPosition;

    } catch (UncategorizedSQLException e) {
        if (e.getCause() instanceof PSQLException) {
            ServerErrorMessage serverError = ((PSQLException) e.getCause()).getServerErrorMessage();
            Matcher m = OPTIMISTIC_LOCKING_FAILURE_MESSAGE.matcher(serverError.getMessage());
            if (m.matches()) {
                String currentVersion = m.group(1);
                throw new OptimisticLockingException("expected version " + expectedVersion + " but was "
                        + currentVersion + " for stream " + streamId, e);
            }
        }
        throw e;
    } catch (SQLException | JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}