Search in sources :

Example 1 with QueryTimeoutException

use of jakarta.persistence.QueryTimeoutException in project hibernate-orm by hibernate.

the class LockTest method testQueryTimeoutEMProps.

@Test
@RequiresDialect(OracleDialect.class)
@RequiresDialectFeature(DialectChecks.SupportsLockTimeouts.class)
public void testQueryTimeoutEMProps() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final Map<String, Object> timeoutProps = new HashMap<String, Object>();
    // 1 sec timeout (should round up)
    timeoutProps.put(HINT_SPEC_QUERY_TIMEOUT, 500);
    final Lock lock = new Lock();
    FutureTask<Boolean> bgTask = new FutureTask<>(() -> {
        try {
            // true (success) if LockTimeoutException occurred
            AtomicBoolean timedOut = new AtomicBoolean();
            doInJPA(this::entityManagerFactory, _entityManager -> {
                log.info("testQueryTimeout: (BG) about to read write-locked entity");
                // we should block on the following read
                Lock lock2 = _entityManager.getReference(Lock.class, lock.getId());
                // force entity to be read
                lock2.getName();
                log.info("testQueryTimeout: (BG) read write-locked entity");
                try {
                    // we should block on the following read
                    Query query = _entityManager.createQuery("select L from Lock_ L where L.id < 10000 ");
                    query.setLockMode(LockModeType.PESSIMISTIC_READ);
                    List<Lock> resultList = query.getResultList();
                    // force entity to be read
                    String name = resultList.get(0).getName();
                    log.info("testQueryTimeout: name read =" + name);
                } catch (QueryTimeoutException e) {
                    // success
                    log.info("testQueryTimeout: (BG) got expected timeout exception");
                    timedOut.set(true);
                } catch (Throwable e) {
                    log.info("Expected LockTimeoutException but got unexpected exception", e);
                }
            }, timeoutProps);
            return timedOut.get();
        } finally {
            // signal that we finished
            latch.countDown();
        }
    });
    Thread t = new Thread(bgTask);
    t.setDaemon(true);
    t.setName("Lock timeout Test (bg)");
    try {
        lock.setName("testQueryTimeout");
        doInJPA(this::entityManagerFactory, em -> {
            em.persist(lock);
        });
        doInJPA(this::entityManagerFactory, em -> {
            Lock _lock = em.getReference(Lock.class, lock.getId());
            em.lock(_lock, LockModeType.PESSIMISTIC_WRITE);
            final Integer id = _lock.getId();
            // force entity to be read
            _lock.getName();
            log.info("testQueryTimeout: got write lock");
            try {
                t.start();
                // should return quickly on success
                boolean latchSet = latch.await(20, TimeUnit.SECONDS);
                assertTrue("background test thread finished (lock timeout is broken)", latchSet);
                assertTrue("background test thread timed out on lock attempt", bgTask.get());
            } catch (InterruptedException e) {
                Thread.interrupted();
            } catch (ExecutionException e) {
                throw new AssertionError(e);
            }
        });
    } finally {
        awaitThenDelete("testQueryTimeoutEMProps", t, lock.getId());
    }
}
Also used : Query(jakarta.persistence.Query) HashMap(java.util.HashMap) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) QueryTimeoutException(jakarta.persistence.QueryTimeoutException) FutureTask(java.util.concurrent.FutureTask) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature) RequiresDialect(org.hibernate.testing.RequiresDialect)

Example 2 with QueryTimeoutException

use of jakarta.persistence.QueryTimeoutException in project hibernate-orm by hibernate.

the class LockTest method testQueryTimeout.

@Test
@RequiresDialect(OracleDialect.class)
@RequiresDialectFeature(DialectChecks.SupportsLockTimeouts.class)
public void testQueryTimeout() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final Lock lock = new Lock();
    FutureTask<Boolean> bgTask = new FutureTask<>(() -> {
        try {
            // true (success) if LockTimeoutException occurred
            AtomicBoolean timedOut = new AtomicBoolean();
            doInJPA(this::entityManagerFactory, _entityManager -> {
                log.info("testQueryTimeout: (BG) about to read write-locked entity");
                // we should block on the following read
                Lock lock2 = _entityManager.getReference(Lock.class, lock.getId());
                // force entity to be read
                lock2.getName();
                log.info("testQueryTimeout: (BG) read write-locked entity");
                try {
                    // we should block on the following read
                    Query query = _entityManager.createQuery("select L from Lock_ L where L.id < 10000 ");
                    query.setLockMode(LockModeType.PESSIMISTIC_READ);
                    // 1 sec timeout
                    query.setHint(HINT_SPEC_QUERY_TIMEOUT, 500);
                    List<Lock> resultList = query.getResultList();
                    // force entity to be read
                    String name = resultList.get(0).getName();
                    log.info("testQueryTimeout: name read =" + name);
                } catch (QueryTimeoutException e) {
                    // success
                    log.info("testQueryTimeout: (BG) got expected timeout exception");
                    timedOut.set(true);
                } catch (Throwable e) {
                    log.info("Expected LockTimeoutException but got unexpected exception", e);
                }
            });
            return timedOut.get();
        } finally {
            // signal that we finished
            latch.countDown();
        }
    });
    Thread t = new Thread(bgTask);
    t.setDaemon(true);
    t.setName("Lock timeout Test (bg)");
    try {
        lock.setName("testQueryTimeout");
        doInJPA(this::entityManagerFactory, em -> {
            em.persist(lock);
        });
        doInJPA(this::entityManagerFactory, em -> {
            Lock _lock = em.getReference(Lock.class, lock.getId());
            em.lock(_lock, LockModeType.PESSIMISTIC_WRITE);
            final Integer id = _lock.getId();
            // force entity to be read
            _lock.getName();
            log.info("testQueryTimeout: got write lock");
            try {
                t.start();
                // should return quickly on success
                boolean latchSet = latch.await(20, TimeUnit.SECONDS);
                assertTrue("background test thread finished (lock timeout is broken)", latchSet);
                assertTrue("background test thread timed out on lock attempt", bgTask.get());
            } catch (InterruptedException e) {
                Thread.interrupted();
            } catch (ExecutionException e) {
                throw new AssertionError(e);
            }
        });
    } finally {
        awaitThenDelete("testQueryTimeout", t, lock.getId());
    }
}
Also used : Query(jakarta.persistence.Query) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) QueryTimeoutException(jakarta.persistence.QueryTimeoutException) FutureTask(java.util.concurrent.FutureTask) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature) RequiresDialect(org.hibernate.testing.RequiresDialect)

Example 3 with QueryTimeoutException

use of jakarta.persistence.QueryTimeoutException in project hibernate-orm by hibernate.

the class ExceptionConverterImpl method convert.

@Override
public RuntimeException convert(HibernateException exception, LockOptions lockOptions) {
    if (exception instanceof StaleStateException) {
        final PersistenceException converted = wrapStaleStateException((StaleStateException) exception);
        handlePersistenceException(converted);
        return converted;
    } else if (exception instanceof LockAcquisitionException) {
        final PersistenceException converted = wrapLockException(exception, lockOptions);
        handlePersistenceException(converted);
        return converted;
    } else if (exception instanceof LockingStrategyException) {
        final PersistenceException converted = wrapLockException(exception, lockOptions);
        handlePersistenceException(converted);
        return converted;
    } else if (exception instanceof org.hibernate.PessimisticLockException) {
        final PersistenceException converted = wrapLockException(exception, lockOptions);
        handlePersistenceException(converted);
        return converted;
    } else if (exception instanceof org.hibernate.QueryTimeoutException) {
        final QueryTimeoutException converted = new QueryTimeoutException(exception.getMessage(), exception);
        handlePersistenceException(converted);
        return converted;
    } else if (exception instanceof ObjectNotFoundException) {
        final EntityNotFoundException converted = new EntityNotFoundException(exception.getMessage());
        handlePersistenceException(converted);
        return converted;
    } else if (exception instanceof org.hibernate.NonUniqueObjectException) {
        final EntityExistsException converted = new EntityExistsException(exception.getMessage());
        handlePersistenceException(converted);
        return converted;
    } else if (exception instanceof org.hibernate.NonUniqueResultException) {
        final NonUniqueResultException converted = new NonUniqueResultException(exception.getMessage());
        handlePersistenceException(converted);
        return converted;
    } else if (exception instanceof UnresolvableObjectException) {
        final EntityNotFoundException converted = new EntityNotFoundException(exception.getMessage());
        handlePersistenceException(converted);
        return converted;
    } else if (exception instanceof SemanticException) {
        return new IllegalArgumentException(exception);
    } else if (exception instanceof QueryException) {
        return new IllegalArgumentException(exception);
    } else if (exception instanceof InterpretationException) {
        return new IllegalArgumentException(exception);
    } else if (exception instanceof ParsingException) {
        return new IllegalArgumentException(exception);
    } else if (exception instanceof MultipleBagFetchException) {
        return new IllegalArgumentException(exception);
    } else if (exception instanceof TransientObjectException) {
        try {
            sharedSessionContract.markForRollbackOnly();
        } catch (Exception ne) {
            // we do not want the subsequent exception to swallow the original one
            log.unableToMarkForRollbackOnTransientObjectException(ne);
        }
        // Spec 3.2.3 Synchronization rules
        return new IllegalStateException(exception);
    } else {
        final PersistenceException converted = new PersistenceException("Converting `" + exception.getClass().getName() + "` to JPA `PersistenceException` : " + exception.getMessage(), exception);
        handlePersistenceException(converted);
        return converted;
    }
}
Also used : NonUniqueResultException(jakarta.persistence.NonUniqueResultException) TransientObjectException(org.hibernate.TransientObjectException) LockingStrategyException(org.hibernate.dialect.lock.LockingStrategyException) EntityNotFoundException(jakarta.persistence.EntityNotFoundException) EntityExistsException(jakarta.persistence.EntityExistsException) LockAcquisitionException(org.hibernate.exception.LockAcquisitionException) MultipleBagFetchException(org.hibernate.loader.MultipleBagFetchException) PessimisticLockException(jakarta.persistence.PessimisticLockException) InterpretationException(org.hibernate.query.sqm.InterpretationException) PersistenceException(jakarta.persistence.PersistenceException) SemanticException(org.hibernate.query.SemanticException) UnresolvableObjectException(org.hibernate.UnresolvableObjectException) SQLException(java.sql.SQLException) JDBCException(org.hibernate.JDBCException) EntityExistsException(jakarta.persistence.EntityExistsException) QueryTimeoutException(jakarta.persistence.QueryTimeoutException) EntityNotFoundException(jakarta.persistence.EntityNotFoundException) StaleStateException(org.hibernate.StaleStateException) OptimisticEntityLockException(org.hibernate.dialect.lock.OptimisticEntityLockException) LockingStrategyException(org.hibernate.dialect.lock.LockingStrategyException) StaleObjectStateException(org.hibernate.StaleObjectStateException) RollbackException(jakarta.persistence.RollbackException) PessimisticEntityLockException(org.hibernate.dialect.lock.PessimisticEntityLockException) TransientObjectException(org.hibernate.TransientObjectException) LockTimeoutException(jakarta.persistence.LockTimeoutException) NonUniqueResultException(jakarta.persistence.NonUniqueResultException) ObjectNotFoundException(org.hibernate.ObjectNotFoundException) ParsingException(org.hibernate.query.sqm.ParsingException) HibernateException(org.hibernate.HibernateException) NoResultException(jakarta.persistence.NoResultException) OptimisticLockException(jakarta.persistence.OptimisticLockException) QueryException(org.hibernate.QueryException) QueryTimeoutException(jakarta.persistence.QueryTimeoutException) QueryException(org.hibernate.QueryException) StaleStateException(org.hibernate.StaleStateException) InterpretationException(org.hibernate.query.sqm.InterpretationException) ObjectNotFoundException(org.hibernate.ObjectNotFoundException) ParsingException(org.hibernate.query.sqm.ParsingException) PersistenceException(jakarta.persistence.PersistenceException) UnresolvableObjectException(org.hibernate.UnresolvableObjectException) MultipleBagFetchException(org.hibernate.loader.MultipleBagFetchException) LockAcquisitionException(org.hibernate.exception.LockAcquisitionException) SemanticException(org.hibernate.query.SemanticException)

Aggregations

QueryTimeoutException (jakarta.persistence.QueryTimeoutException)3 Query (jakarta.persistence.Query)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 ExecutionException (java.util.concurrent.ExecutionException)2 FutureTask (java.util.concurrent.FutureTask)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 RequiresDialect (org.hibernate.testing.RequiresDialect)2 RequiresDialectFeature (org.hibernate.testing.RequiresDialectFeature)2 Test (org.junit.Test)2 EntityExistsException (jakarta.persistence.EntityExistsException)1 EntityNotFoundException (jakarta.persistence.EntityNotFoundException)1 LockTimeoutException (jakarta.persistence.LockTimeoutException)1 NoResultException (jakarta.persistence.NoResultException)1 NonUniqueResultException (jakarta.persistence.NonUniqueResultException)1 OptimisticLockException (jakarta.persistence.OptimisticLockException)1 PersistenceException (jakarta.persistence.PersistenceException)1 PessimisticLockException (jakarta.persistence.PessimisticLockException)1 RollbackException (jakarta.persistence.RollbackException)1 SQLException (java.sql.SQLException)1 HashMap (java.util.HashMap)1