Search in sources :

Example 1 with GenericJDBCException

use of org.hibernate.exception.GenericJDBCException in project hibernate-orm by hibernate.

the class SequenceValueExtractor method extractSequenceValue.

public long extractSequenceValue(final SessionImplementor sessionImpl) {
    class WorkImpl implements Work {

        private long value;

        public void execute(Connection connection) throws SQLException {
            Session session = (Session) sessionImpl;
            Transaction transaction = session.beginTransaction();
            try {
                final PreparedStatement query = sessionImpl.getJdbcCoordinator().getStatementPreparer().prepareStatement(queryString);
                ResultSet resultSet = sessionImpl.getJdbcCoordinator().getResultSetReturn().extract(query);
                resultSet.next();
                value = resultSet.getLong(1);
                resultSet.close();
                transaction.commit();
            } catch (GenericJDBCException e) {
                transaction.rollback();
                throw e;
            }
            if (dialect instanceof DerbyDialect) {
                value--;
            }
        }
    }
    WorkImpl work = new WorkImpl();
    ((Session) sessionImpl).doWork(work);
    return work.value;
}
Also used : DerbyDialect(org.hibernate.dialect.DerbyDialect) Transaction(org.hibernate.Transaction) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) Work(org.hibernate.jdbc.Work) PreparedStatement(java.sql.PreparedStatement) GenericJDBCException(org.hibernate.exception.GenericJDBCException) Session(org.hibernate.Session)

Example 2 with GenericJDBCException

use of org.hibernate.exception.GenericJDBCException in project stdlib by petergeneric.

the class TransactionMethodInterceptor method invoke.

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    if (sessionProvider.get().getTransaction().getStatus() == TransactionStatus.ACTIVE) {
        // allow silent joining of enclosing transactional methods (NOTE: this ignores the current method's txn-al settings)
        if (log.isTraceEnabled())
            log.trace("Joining existing transaction to call " + invocation.getMethod().toGenericString());
        return invocation.proceed();
    } else {
        Timer.Context callTimer = calls.time();
        final String tracingId = Tracing.log("TX:begin", () -> invocation.getMethod().toGenericString());
        try {
            final Transactional annotation = readAnnotation(invocation);
            // After the max attempts for auto retry are exhausted we'll fall back on the non-retrying default behaviour
            if (annotation.autoRetry()) {
                // Try all but the last attempt
                final int retries = Math.max(0, annotation.autoRetryCount() - 1);
                // N.B. more aggressive than the @Retry annotation implements
                long backoff = 1000;
                final double multiplier = 1.5;
                for (int attempt = 0; attempt < retries; attempt++) {
                    try {
                        return createTransactionAndExecuteMethod(invocation, annotation);
                    } catch (LockAcquisitionException | StaleStateException | GenericJDBCException | OptimisticLockException e) {
                        if (log.isTraceEnabled())
                            log.warn("@Transactional caught exception " + e.getClass().getSimpleName() + "; retrying...", e);
                        else
                            log.warn("@Transactional caught exception " + e.getClass().getSimpleName() + "; retrying...");
                        Tracing.logOngoing(tracingId, "TX:exception:retryable", () -> e.getClass().getSimpleName());
                        try {
                            Thread.sleep(backoff);
                        } catch (InterruptedException ie) {
                            throw new RuntimeException("Interrupted while attempting a @Transactional retry!", ie);
                        }
                        // Increase backoff for the next exception
                        backoff *= multiplier;
                    } catch (PersistenceException e) {
                        // Handle generic exception (usually one that wraps another exception)
                        if (e.getCause() != null && (isSqlServerSnapshotConflictError(e) || isDeadlockError(e))) {
                            if (log.isTraceEnabled())
                                log.warn("@Transactional caught exception PersistenceException wrapping " + e.getCause().getClass().getSimpleName() + "; retrying...", e);
                            else
                                log.warn("@Transactional caught exception PersistenceException wrapping " + e.getCause().getClass().getSimpleName() + "; retrying...");
                            Tracing.logOngoing(tracingId, "TX:exception:retryable:wrapped", () -> e.getCause().getClass().getSimpleName());
                            try {
                                Thread.sleep(backoff);
                            } catch (InterruptedException ie) {
                                throw new RuntimeException("Interrupted while attempting a @Transactional retry!", ie);
                            }
                            // Increase backoff for the next exception
                            backoff *= multiplier;
                        } else {
                            Tracing.logOngoing(tracingId, "TX:exception:fatal", () -> e.getClass().getSimpleName());
                            // rethrow because we won't handle this
                            throw e;
                        }
                    }
                }
            }
            Tracing.logOngoing(tracingId, "TX:last-try", null);
            // Run without further retries
            return createTransactionAndExecuteMethod(invocation, annotation);
        } finally {
            Tracing.logOngoing(tracingId, "TX:quit", null);
            callTimer.stop();
        }
    }
}
Also used : OptimisticLockException(javax.persistence.OptimisticLockException) Timer(com.codahale.metrics.Timer) StaleStateException(org.hibernate.StaleStateException) PersistenceException(javax.persistence.PersistenceException) GenericJDBCException(org.hibernate.exception.GenericJDBCException) Transactional(com.peterphi.std.guice.database.annotation.Transactional) LockAcquisitionException(org.hibernate.exception.LockAcquisitionException)

Example 3 with GenericJDBCException

use of org.hibernate.exception.GenericJDBCException in project head by mifos.

the class LegacyGenericDao method execUniqueResultNamedQueryWithResultTransformer.

@SuppressWarnings("unchecked")
public <T extends Object> T execUniqueResultNamedQueryWithResultTransformer(final String queryName, final Map<String, ?> queryParameters, final Class<T> clazz) {
    try {
        Query query = getSession().getNamedQuery(queryName).setResultTransformer(Transformers.aliasToBean(clazz));
        query.setProperties(queryParameters);
        query.setResultTransformer(Transformers.aliasToBean(clazz));
        return (T) query.uniqueResult();
    } catch (GenericJDBCException gje) {
        throw new ConnectionNotFoundException(gje);
    } catch (Exception e) {
        throw new MifosRuntimeException(e);
    }
}
Also used : ConnectionNotFoundException(org.mifos.framework.exceptions.ConnectionNotFoundException) Query(org.hibernate.Query) GenericJDBCException(org.hibernate.exception.GenericJDBCException) ConnectionNotFoundException(org.mifos.framework.exceptions.ConnectionNotFoundException) MifosRuntimeException(org.mifos.core.MifosRuntimeException) PersistenceException(org.mifos.framework.exceptions.PersistenceException) GenericJDBCException(org.hibernate.exception.GenericJDBCException) HibernateException(org.hibernate.HibernateException) MifosRuntimeException(org.mifos.core.MifosRuntimeException)

Example 4 with GenericJDBCException

use of org.hibernate.exception.GenericJDBCException in project head by mifos.

the class LegacyGenericDao method execUniqueResultNamedQueryWithoutFlush.

public Object execUniqueResultNamedQueryWithoutFlush(final String queryName, final Map<String, ?> queryParameters) throws PersistenceException {
    try {
        Session sess = getSession();
        sess.setFlushMode(FlushMode.MANUAL);
        Query query = getSession().getNamedQuery(queryName);
        logger.debug("The query object for the query with the name  " + queryName + " has been obtained");
        query.setProperties(queryParameters);
        Object returnObject = query.uniqueResult();
        sess.setFlushMode(FlushMode.AUTO);
        return returnObject;
    } catch (GenericJDBCException gje) {
        throw new ConnectionNotFoundException(gje);
    } catch (Exception e) {
        throw new PersistenceException(e);
    }
}
Also used : ConnectionNotFoundException(org.mifos.framework.exceptions.ConnectionNotFoundException) Query(org.hibernate.Query) PersistenceException(org.mifos.framework.exceptions.PersistenceException) GenericJDBCException(org.hibernate.exception.GenericJDBCException) ConnectionNotFoundException(org.mifos.framework.exceptions.ConnectionNotFoundException) MifosRuntimeException(org.mifos.core.MifosRuntimeException) PersistenceException(org.mifos.framework.exceptions.PersistenceException) GenericJDBCException(org.hibernate.exception.GenericJDBCException) HibernateException(org.hibernate.HibernateException) Session(org.hibernate.Session)

Example 5 with GenericJDBCException

use of org.hibernate.exception.GenericJDBCException in project head by mifos.

the class LegacyGenericDao method execUniqueResultNamedQuery.

public Object execUniqueResultNamedQuery(final String queryName, final Map<String, ?> queryParameters) throws PersistenceException {
    try {
        Query query = getSession().getNamedQuery(queryName);
        logger.debug("The query object for the query with the name  " + queryName + " has been obtained");
        query.setProperties(queryParameters);
        return query.uniqueResult();
    } catch (GenericJDBCException gje) {
        throw new ConnectionNotFoundException(gje);
    } catch (Exception e) {
        throw new PersistenceException(e);
    }
}
Also used : ConnectionNotFoundException(org.mifos.framework.exceptions.ConnectionNotFoundException) Query(org.hibernate.Query) PersistenceException(org.mifos.framework.exceptions.PersistenceException) GenericJDBCException(org.hibernate.exception.GenericJDBCException) ConnectionNotFoundException(org.mifos.framework.exceptions.ConnectionNotFoundException) MifosRuntimeException(org.mifos.core.MifosRuntimeException) PersistenceException(org.mifos.framework.exceptions.PersistenceException) GenericJDBCException(org.hibernate.exception.GenericJDBCException) HibernateException(org.hibernate.HibernateException)

Aggregations

GenericJDBCException (org.hibernate.exception.GenericJDBCException)6 HibernateException (org.hibernate.HibernateException)3 Query (org.hibernate.Query)3 MifosRuntimeException (org.mifos.core.MifosRuntimeException)3 ConnectionNotFoundException (org.mifos.framework.exceptions.ConnectionNotFoundException)3 PersistenceException (org.mifos.framework.exceptions.PersistenceException)3 Session (org.hibernate.Session)2 Transaction (org.hibernate.Transaction)2 Timer (com.codahale.metrics.Timer)1 Transactional (com.peterphi.std.guice.database.annotation.Transactional)1 Connection (java.sql.Connection)1 PreparedStatement (java.sql.PreparedStatement)1 ResultSet (java.sql.ResultSet)1 SQLException (java.sql.SQLException)1 OptimisticLockException (javax.persistence.OptimisticLockException)1 PersistenceException (javax.persistence.PersistenceException)1 StaleStateException (org.hibernate.StaleStateException)1 DerbyDialect (org.hibernate.dialect.DerbyDialect)1 LockAcquisitionException (org.hibernate.exception.LockAcquisitionException)1 Work (org.hibernate.jdbc.Work)1