Search in sources :

Example 11 with LockTimeoutException

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

the class LockExceptionTests method testLockTimeoutLock.

@Test
public void testLockTimeoutLock() {
    final Item item = new Item("lock");
    inTransaction(session -> session.persist(item));
    try {
        inTransaction(session -> {
            session.find(Item.class, item.getId(), LockModeType.PESSIMISTIC_WRITE);
            TransactionUtil2.inTransaction(sessionFactory(), secondSession -> {
                try {
                    // generally speaking we should be able to read the row
                    Item item2 = secondSession.get(Item.class, item.getId());
                    secondSession.lock(item2, LockModeType.PESSIMISTIC_WRITE, Collections.singletonMap(AvailableSettings.JAKARTA_LOCK_TIMEOUT, LockOptions.NO_WAIT));
                    fail("Expecting a failure");
                } catch (LockTimeoutException | PessimisticLockException expected) {
                // expected outcome
                }
            });
        });
    } finally {
        inTransaction(session -> session.createQuery("delete Item").executeUpdate());
    }
}
Also used : Item(org.hibernate.orm.test.jpa.model.Item) LockTimeoutException(jakarta.persistence.LockTimeoutException) PessimisticLockException(jakarta.persistence.PessimisticLockException) AbstractJPATest(org.hibernate.orm.test.jpa.model.AbstractJPATest) Test(org.junit.jupiter.api.Test)

Example 12 with LockTimeoutException

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

the class ExceptionConverterImpl method wrapLockException.

protected PersistenceException wrapLockException(HibernateException e, LockOptions lockOptions) {
    final PersistenceException pe;
    if (e instanceof OptimisticEntityLockException) {
        final OptimisticEntityLockException lockException = (OptimisticEntityLockException) e;
        pe = new OptimisticLockException(lockException.getMessage(), lockException, lockException.getEntity());
    } else if (e instanceof org.hibernate.exception.LockTimeoutException) {
        pe = new LockTimeoutException(e.getMessage(), e, null);
    } else if (e instanceof PessimisticEntityLockException) {
        final PessimisticEntityLockException lockException = (PessimisticEntityLockException) e;
        if (lockOptions != null && lockOptions.getTimeOut() > -1) {
            // assume lock timeout occurred if a timeout or NO WAIT was specified
            pe = new LockTimeoutException(lockException.getMessage(), lockException, lockException.getEntity());
        } else {
            pe = new PessimisticLockException(lockException.getMessage(), lockException, lockException.getEntity());
        }
    } else if (e instanceof org.hibernate.PessimisticLockException) {
        final org.hibernate.PessimisticLockException jdbcLockException = (org.hibernate.PessimisticLockException) e;
        if (lockOptions != null && lockOptions.getTimeOut() > -1) {
            // assume lock timeout occurred if a timeout or NO WAIT was specified
            pe = new LockTimeoutException(jdbcLockException.getMessage(), jdbcLockException, null);
        } else {
            pe = new PessimisticLockException(jdbcLockException.getMessage(), jdbcLockException, null);
        }
    } else {
        pe = new OptimisticLockException(e);
    }
    return pe;
}
Also used : PessimisticEntityLockException(org.hibernate.dialect.lock.PessimisticEntityLockException) PersistenceException(jakarta.persistence.PersistenceException) OptimisticLockException(jakarta.persistence.OptimisticLockException) LockTimeoutException(jakarta.persistence.LockTimeoutException) OptimisticEntityLockException(org.hibernate.dialect.lock.OptimisticEntityLockException) PessimisticLockException(jakarta.persistence.PessimisticLockException)

Example 13 with LockTimeoutException

use of jakarta.persistence.LockTimeoutException in project eclipselink by eclipse-ee4j.

the class EJBQueryImpl method getResultCursor.

/**
 * Non-standard method to return results of a ReadQuery that uses a Cursor.
 *
 * @return Cursor on results, either a CursoredStream, or ScrollableCursor
 */
@Override
public Cursor getResultCursor() {
    // bug51411440: need to throw IllegalStateException if query executed on closed em
    this.entityManager.verifyOpenWithSetRollbackOnly();
    try {
        setAsSQLReadQuery();
        propagateResultProperties();
        // not the right type
        if (getDatabaseQueryInternal() instanceof ReadAllQuery) {
            if (!((ReadAllQuery) getDatabaseQueryInternal()).getContainerPolicy().isCursorPolicy()) {
                Class<?> containerClass = ((ReadAllQuery) getDatabaseQueryInternal()).getContainerPolicy().getContainerClass();
                throw QueryException.invalidContainerClass(containerClass, Cursor.class);
            }
        } else if (getDatabaseQueryInternal() instanceof ReadObjectQuery) {
            // bug:4300879, no support for ReadObjectQuery if a collection is required
            throw QueryException.incorrectQueryObjectFound(getDatabaseQueryInternal(), ReadAllQuery.class);
        } else if (!(getDatabaseQueryInternal() instanceof ReadQuery)) {
            throw new IllegalStateException(ExceptionLocalization.buildMessage("incorrect_query_for_get_result_collection"));
        }
        Object result = executeReadQuery();
        return (Cursor) result;
    } catch (LockTimeoutException e) {
        throw e;
    } catch (PersistenceException exception) {
        setRollbackOnly();
        throw exception;
    } catch (IllegalStateException exception) {
        setRollbackOnly();
        throw exception;
    } catch (RuntimeException exception) {
        setRollbackOnly();
        throw new PersistenceException(exception);
    }
}
Also used : ReadObjectQuery(org.eclipse.persistence.queries.ReadObjectQuery) ReadAllQuery(org.eclipse.persistence.queries.ReadAllQuery) PersistenceException(jakarta.persistence.PersistenceException) Cursor(org.eclipse.persistence.queries.Cursor) ObjectLevelReadQuery(org.eclipse.persistence.queries.ObjectLevelReadQuery) DataReadQuery(org.eclipse.persistence.queries.DataReadQuery) ReadQuery(org.eclipse.persistence.queries.ReadQuery) LockTimeoutException(jakarta.persistence.LockTimeoutException)

Example 14 with LockTimeoutException

use of jakarta.persistence.LockTimeoutException in project eclipselink by eclipse-ee4j.

the class EntityManagerImpl method lock.

/**
 * Set the lock mode for an entity object contained in the persistence
 * context.
 *
 * @throws PersistenceException
 *             if an unsupported lock call is made
 * @throws IllegalArgumentException
 *             if the instance is not an entity or is a detached entity
 * @throws jakarta.persistence.TransactionRequiredException
 *             if there is no transaction
 */
@Override
public void lock(Object entity, LockModeType lockMode, Map<String, Object> properties) {
    try {
        verifyOpen();
        if (entity == null) {
            throw new IllegalArgumentException(ExceptionLocalization.buildMessage("not_an_entity", new Object[] { null }));
        }
        // Throws TransactionRequiredException if no active transaction.
        UnitOfWorkImpl uow = getActivePersistenceContext(checkForTransaction(true));
        if (!contains(entity, uow)) {
            throw new IllegalArgumentException(ExceptionLocalization.buildMessage("cant_lock_not_managed_object", new Object[] { entity }));
        }
        if (lockMode == null || lockMode.name().equals(ObjectLevelReadQuery.NONE)) {
            // Nothing to do
            return;
        }
        // Must avoid using the new JPA 2.0 Enum values directly to allow JPA 1.0 jars to still work.
        if (lockMode.name().equals(ObjectLevelReadQuery.PESSIMISTIC_READ) || lockMode.name().equals(ObjectLevelReadQuery.PESSIMISTIC_WRITE) || lockMode.name().equals(ObjectLevelReadQuery.PESSIMISTIC_FORCE_INCREMENT)) {
            // return if the entity has previously been pessimistically locked
            if (uow.isPessimisticLocked(entity)) {
                return;
            }
            // Get the read object query and apply the properties to it.
            ReadObjectQuery query = getReadObjectQuery(entity, properties);
            // the properties.
            if (properties == null || !properties.containsKey(QueryHints.REFRESH)) {
                query.refreshIdentityMapResult();
            }
            if (properties == null || !properties.containsKey(QueryHints.REFRESH_CASCADE)) {
                query.cascadePrivateParts();
            }
            executeQuery(query, lockMode, getActivePersistenceContext(checkForTransaction(false)));
        } else {
            RepeatableWriteUnitOfWork context = getActivePersistenceContext(checkForTransaction(false));
            ClassDescriptor descriptor = context.getDescriptor(entity);
            OptimisticLockingPolicy lockingPolicy = descriptor.getOptimisticLockingPolicy();
            if ((lockingPolicy == null) || !(lockingPolicy instanceof VersionLockingPolicy)) {
                throw new PersistenceException(ExceptionLocalization.buildMessage("ejb30-wrong-lock_called_without_version_locking-index", null));
            }
            context.forceUpdateToVersionField(entity, (lockMode == LockModeType.WRITE || lockMode.name().equals(ObjectLevelReadQuery.OPTIMISTIC_FORCE_INCREMENT)));
        }
    } catch (LockTimeoutException e) {
        throw e;
    } catch (RuntimeException e) {
        setRollbackOnly();
        throw e;
    }
}
Also used : ReadObjectQuery(org.eclipse.persistence.queries.ReadObjectQuery) ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) VersionLockingPolicy(org.eclipse.persistence.descriptors.VersionLockingPolicy) PersistenceException(jakarta.persistence.PersistenceException) UnitOfWorkImpl(org.eclipse.persistence.internal.sessions.UnitOfWorkImpl) RepeatableWriteUnitOfWork(org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork) LockTimeoutException(jakarta.persistence.LockTimeoutException) OptimisticLockingPolicy(org.eclipse.persistence.internal.descriptors.OptimisticLockingPolicy)

Example 15 with LockTimeoutException

use of jakarta.persistence.LockTimeoutException in project eclipselink by eclipse-ee4j.

the class EntityManagerImpl method refresh.

/**
 * Refresh the state of the instance from the database, overwriting changes
 * made to the entity, if any, and lock it with respect to given lock mode
 * type. If the lock mode type is pessimistic and the entity instance is
 * found but cannot be locked: - the PessimisticLockException will be thrown
 * if the database locking failure causes transaction-level rollback. - the
 * LockTimeoutException will be thrown if the database locking failure
 * causes only statement-level rollback If a vendor-specific property or
 * hint is not recognized, it is silently ignored. Portable applications
 * should not rely on the standard timeout hint. Depending on the database
 * in use and the locking mechanisms used by the provider, the hint may or
 * may not be observed.
 *
 * @param properties
 *            standard and vendor-specific properties and hints
 * @throws IllegalArgumentException
 *             if the instance is not an entity or the entity is not managed
 * @throws TransactionRequiredException
 *             if there is no transaction
 * @throws EntityNotFoundException
 *             if the entity no longer exists in the database
 * @throws PessimisticLockException
 *             if pessimistic locking fails and the transaction is rolled
 *             back
 * @throws LockTimeoutException
 *             if pessimistic locking fails and only the statement is rolled
 *             back
 * @throws PersistenceException
 *             if an unsupported lock call is made
 */
@Override
public void refresh(Object entity, LockModeType lockMode, Map<String, Object> properties) {
    try {
        verifyOpen();
        boolean validateExistence = (lockMode != null && !lockMode.equals(LockModeType.NONE));
        UnitOfWorkImpl uow = getActivePersistenceContext(checkForTransaction(validateExistence));
        if (!contains(entity, uow)) {
            throw new IllegalArgumentException(ExceptionLocalization.buildMessage("cant_refresh_not_managed_object", new Object[] { entity }));
        }
        // Get the read object query and apply the properties to it.
        ReadObjectQuery query = getReadObjectQuery(entity, properties);
        // the properties.
        if (properties == null || !properties.containsKey(QueryHints.REFRESH)) {
            query.refreshIdentityMapResult();
        }
        if (properties == null || !properties.containsKey(QueryHints.REFRESH_CASCADE)) {
            query.cascadeByMapping();
        }
        Object refreshedEntity = executeQuery(query, lockMode, uow);
        if (refreshedEntity == null) {
            // invalidated if refresh returns null.
            throw new EntityNotFoundException(ExceptionLocalization.buildMessage("entity_no_longer_exists_in_db", new Object[] { entity }));
        }
    } catch (LockTimeoutException e) {
        throw e;
    } catch (RuntimeException exception) {
        setRollbackOnly();
        throw exception;
    }
}
Also used : ReadObjectQuery(org.eclipse.persistence.queries.ReadObjectQuery) UnitOfWorkImpl(org.eclipse.persistence.internal.sessions.UnitOfWorkImpl) EntityNotFoundException(jakarta.persistence.EntityNotFoundException) LockTimeoutException(jakarta.persistence.LockTimeoutException)

Aggregations

LockTimeoutException (jakarta.persistence.LockTimeoutException)20 PersistenceException (jakarta.persistence.PersistenceException)10 PessimisticLockException (jakarta.persistence.PessimisticLockException)5 List (java.util.List)5 ExecutionException (java.util.concurrent.ExecutionException)5 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)5 RequiresDialectFeature (org.hibernate.testing.RequiresDialectFeature)5 Test (org.junit.Test)5 HashMap (java.util.HashMap)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 FutureTask (java.util.concurrent.FutureTask)4 RequiresDialect (org.hibernate.testing.RequiresDialect)4 QueryTimeoutException (jakarta.persistence.QueryTimeoutException)3 ArrayList (java.util.ArrayList)3 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)3 ReadObjectQuery (org.eclipse.persistence.queries.ReadObjectQuery)3 AbstractJPATest (org.hibernate.orm.test.jpa.model.AbstractJPATest)3 Item (org.hibernate.orm.test.jpa.model.Item)3 Test (org.junit.jupiter.api.Test)3 OptimisticLockException (jakarta.persistence.OptimisticLockException)2