Search in sources :

Example 1 with StaleStateException

use of org.hibernate.StaleStateException in project hibernate-orm by hibernate.

the class VersionedTest method testStaleRead.

protected ByRef<Object> testStaleRead(BiConsumer<Session, Item> consumer) throws Exception {
    AtomicReference<Exception> synchronizationException = new AtomicReference<>();
    CountDownLatch syncLatch = new CountDownLatch(1);
    CountDownLatch commitLatch = new CountDownLatch(1);
    Future<Boolean> action = executor.submit(() -> withTxSessionApply(s -> {
        try {
            ((SharedSessionContractImplementor) s).getTransactionCoordinator().getLocalSynchronizations().registerSynchronization(new Synchronization() {

                @Override
                public void beforeCompletion() {
                }

                @Override
                public void afterCompletion(int i) {
                    syncLatch.countDown();
                    try {
                        awaitOrThrow(commitLatch);
                    } catch (Exception e) {
                        synchronizationException.set(e);
                    }
                }
            });
            Item item = s.load(Item.class, itemId);
            consumer.accept(s, item);
            s.flush();
        } catch (StaleStateException e) {
            log.info("Exception thrown: ", e);
            markRollbackOnly(s);
            return false;
        } catch (PessimisticLockException e) {
            log.info("Exception thrown: ", e);
            markRollbackOnly(s);
            return false;
        }
        return true;
    }));
    awaitOrThrow(syncLatch);
    ByRef<Object> entryRef = new ByRef<>(null);
    try {
        withTxSession(s -> {
            Item item = s.load(Item.class, itemId);
            assertEquals("Original item", item.getDescription());
            entryRef.set(assertSingleCacheEntry());
        });
    } finally {
        commitLatch.countDown();
    }
    assertTrue(action.get(WAIT_TIMEOUT, TimeUnit.SECONDS));
    assertNull(synchronizationException.get());
    return entryRef;
}
Also used : BaseTransactionalDataRegion(org.hibernate.cache.infinispan.impl.BaseTransactionalDataRegion) Arrays(java.util.Arrays) VersionedEntry(org.hibernate.cache.infinispan.util.VersionedEntry) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Session(org.hibernate.Session) Caches(org.hibernate.cache.infinispan.util.Caches) AtomicReference(java.util.concurrent.atomic.AtomicReference) Future(java.util.concurrent.Future) PessimisticLockException(org.hibernate.PessimisticLockException) InvocationContext(org.infinispan.context.InvocationContext) AdvancedCache(org.infinispan.AdvancedCache) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) Item(org.hibernate.test.cache.infinispan.functional.entities.Item) OtherItem(org.hibernate.test.cache.infinispan.functional.entities.OtherItem) Synchronization(javax.transaction.Synchronization) StaleStateException(org.hibernate.StaleStateException) CyclicBarrier(java.util.concurrent.CyclicBarrier) ByRef(org.infinispan.commons.util.ByRef) Set(java.util.Set) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) BaseCustomInterceptor(org.infinispan.interceptors.base.BaseCustomInterceptor) Assert.assertNull(org.junit.Assert.assertNull) Flag(org.infinispan.context.Flag) Assert.assertFalse(org.junit.Assert.assertFalse) PutKeyValueCommand(org.infinispan.commands.write.PutKeyValueCommand) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) ByRef(org.infinispan.commons.util.ByRef) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) Synchronization(javax.transaction.Synchronization) PessimisticLockException(org.hibernate.PessimisticLockException) StaleStateException(org.hibernate.StaleStateException) PessimisticLockException(org.hibernate.PessimisticLockException) Item(org.hibernate.test.cache.infinispan.functional.entities.Item) OtherItem(org.hibernate.test.cache.infinispan.functional.entities.OtherItem) StaleStateException(org.hibernate.StaleStateException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 2 with StaleStateException

use of org.hibernate.StaleStateException in project hibernate-orm by hibernate.

the class ExceptionConverterImpl method convert.

@Override
public RuntimeException convert(HibernateException e, LockOptions lockOptions) {
    Throwable cause = e;
    if (cause instanceof StaleStateException) {
        final PersistenceException converted = wrapStaleStateException((StaleStateException) cause);
        handlePersistenceException(converted);
        return converted;
    } else if (cause instanceof LockingStrategyException) {
        final PersistenceException converted = wrapLockException((HibernateException) cause, lockOptions);
        handlePersistenceException(converted);
        return converted;
    } else if (cause instanceof org.hibernate.exception.LockTimeoutException) {
        final PersistenceException converted = wrapLockException((HibernateException) cause, lockOptions);
        handlePersistenceException(converted);
        return converted;
    } else if (cause instanceof org.hibernate.PessimisticLockException) {
        final PersistenceException converted = wrapLockException((HibernateException) cause, lockOptions);
        handlePersistenceException(converted);
        return converted;
    } else if (cause instanceof org.hibernate.QueryTimeoutException) {
        final QueryTimeoutException converted = new QueryTimeoutException(cause.getMessage(), cause);
        handlePersistenceException(converted);
        return converted;
    } else if (cause instanceof ObjectNotFoundException) {
        final EntityNotFoundException converted = new EntityNotFoundException(cause.getMessage());
        handlePersistenceException(converted);
        return converted;
    } else if (cause instanceof org.hibernate.NonUniqueObjectException) {
        final EntityExistsException converted = new EntityExistsException(cause.getMessage());
        handlePersistenceException(converted);
        return converted;
    } else if (cause instanceof org.hibernate.NonUniqueResultException) {
        final NonUniqueResultException converted = new NonUniqueResultException(cause.getMessage());
        handlePersistenceException(converted);
        return converted;
    } else if (cause instanceof UnresolvableObjectException) {
        final EntityNotFoundException converted = new EntityNotFoundException(cause.getMessage());
        handlePersistenceException(converted);
        return converted;
    } else if (cause instanceof QueryException) {
        return new IllegalArgumentException(cause);
    } else if (cause instanceof MultipleBagFetchException) {
        return new IllegalArgumentException(cause);
    } else if (cause 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(e);
    } else {
        final PersistenceException converted = new PersistenceException(cause);
        handlePersistenceException(converted);
        return converted;
    }
}
Also used : NonUniqueResultException(javax.persistence.NonUniqueResultException) TransientObjectException(org.hibernate.TransientObjectException) HibernateException(org.hibernate.HibernateException) LockingStrategyException(org.hibernate.dialect.lock.LockingStrategyException) EntityNotFoundException(javax.persistence.EntityNotFoundException) EntityExistsException(javax.persistence.EntityExistsException) LockTimeoutException(javax.persistence.LockTimeoutException) MultipleBagFetchException(org.hibernate.loader.MultipleBagFetchException) NoResultException(javax.persistence.NoResultException) UnresolvableObjectException(org.hibernate.UnresolvableObjectException) SQLException(java.sql.SQLException) NonUniqueResultException(javax.persistence.NonUniqueResultException) JDBCException(org.hibernate.JDBCException) EntityNotFoundException(javax.persistence.EntityNotFoundException) StaleStateException(org.hibernate.StaleStateException) OptimisticEntityLockException(org.hibernate.dialect.lock.OptimisticEntityLockException) LockingStrategyException(org.hibernate.dialect.lock.LockingStrategyException) EntityExistsException(javax.persistence.EntityExistsException) OptimisticLockException(javax.persistence.OptimisticLockException) StaleObjectStateException(org.hibernate.StaleObjectStateException) PessimisticLockException(javax.persistence.PessimisticLockException) PessimisticEntityLockException(org.hibernate.dialect.lock.PessimisticEntityLockException) TransientObjectException(org.hibernate.TransientObjectException) PersistenceException(javax.persistence.PersistenceException) RollbackException(javax.persistence.RollbackException) QueryTimeoutException(javax.persistence.QueryTimeoutException) ObjectNotFoundException(org.hibernate.ObjectNotFoundException) HibernateException(org.hibernate.HibernateException) QueryException(org.hibernate.QueryException) QueryTimeoutException(javax.persistence.QueryTimeoutException) QueryException(org.hibernate.QueryException) StaleStateException(org.hibernate.StaleStateException) ObjectNotFoundException(org.hibernate.ObjectNotFoundException) PersistenceException(javax.persistence.PersistenceException) UnresolvableObjectException(org.hibernate.UnresolvableObjectException) LockTimeoutException(javax.persistence.LockTimeoutException) MultipleBagFetchException(org.hibernate.loader.MultipleBagFetchException)

Example 3 with StaleStateException

use of org.hibernate.StaleStateException in project hibernate-orm by hibernate.

the class EntityTest method testVersion.

@Test
public void testVersion() throws Exception {
    //		put an object in DB
    Session s = openSession();
    Transaction tx = s.beginTransaction();
    Flight firstOne = new Flight();
    firstOne.setId(Long.valueOf(2));
    firstOne.setName("AF3202");
    firstOne.setDuration(Long.valueOf(500));
    s.save(firstOne);
    s.flush();
    tx.commit();
    s.close();
    //read it
    s = openSession();
    tx = s.beginTransaction();
    firstOne = (Flight) s.get(Flight.class, Long.valueOf(2));
    tx.commit();
    s.close();
    //read it again
    s = openSession();
    tx = s.beginTransaction();
    Flight concurrentOne = (Flight) s.get(Flight.class, Long.valueOf(2));
    concurrentOne.setDuration(Long.valueOf(1000));
    s.update(concurrentOne);
    tx.commit();
    s.close();
    assertFalse(firstOne == concurrentOne);
    assertFalse(firstOne.getVersion().equals(concurrentOne.getVersion()));
    //reattach the first one
    s = openSession();
    tx = s.beginTransaction();
    firstOne.setName("Second access");
    s.update(firstOne);
    try {
        tx.commit();
        fail("Optimistic locking should work");
    } catch (PersistenceException expected) {
        if (expected.getCause() instanceof StaleStateException) {
        //expected
        } else {
            fail("StaleStateException expected but is " + expected.getCause());
        }
    } finally {
        if (tx != null) {
            tx.rollback();
        }
        s.close();
    }
}
Also used : Transaction(org.hibernate.Transaction) StaleStateException(org.hibernate.StaleStateException) PersistenceException(javax.persistence.PersistenceException) Session(org.hibernate.Session) Test(org.junit.Test)

Example 4 with StaleStateException

use of org.hibernate.StaleStateException in project ignite by apache.

the class HibernateL2CacheSelfTest method testVersionedEntity.

/**
     * @param accessType Cache access type.
     * @throws Exception If failed.
     */
private void testVersionedEntity(AccessType accessType) throws Exception {
    createSessionFactories(accessType);
    try {
        Session ses = sesFactory1.openSession();
        VersionedEntity e0 = new VersionedEntity(0);
        try {
            Transaction tx = ses.beginTransaction();
            ses.save(e0);
            tx.commit();
        } finally {
            ses.close();
        }
        ses = sesFactory1.openSession();
        long ver;
        try {
            ver = ((VersionedEntity) ses.load(VersionedEntity.class, 0)).getVersion();
        } finally {
            ses.close();
        }
        SecondLevelCacheStatistics stats1 = sesFactory1.getStatistics().getSecondLevelCacheStatistics(VERSIONED_ENTITY_NAME);
        SecondLevelCacheStatistics stats2 = sesFactory2.getStatistics().getSecondLevelCacheStatistics(VERSIONED_ENTITY_NAME);
        assertEquals(1, stats1.getElementCountInMemory());
        assertEquals(1, stats2.getElementCountInMemory());
        ses = sesFactory2.openSession();
        try {
            assertEquals(ver, ((VersionedEntity) ses.load(VersionedEntity.class, 0)).getVersion());
        } finally {
            ses.close();
        }
        assertEquals(1, stats2.getElementCountInMemory());
        assertEquals(1, stats2.getHitCount());
        if (accessType == AccessType.READ_ONLY)
            return;
        e0.setVersion(ver - 1);
        ses = sesFactory1.openSession();
        Transaction tx = ses.beginTransaction();
        try {
            ses.update(e0);
            tx.commit();
            fail("Commit must fail.");
        } catch (StaleStateException e) {
            log.info("Expected exception: " + e);
        } finally {
            tx.rollback();
            ses.close();
        }
        sesFactory1.getStatistics().clear();
        stats1 = sesFactory1.getStatistics().getSecondLevelCacheStatistics(VERSIONED_ENTITY_NAME);
        ses = sesFactory1.openSession();
        try {
            assertEquals(ver, ((VersionedEntity) ses.load(VersionedEntity.class, 0)).getVersion());
        } finally {
            ses.close();
        }
        assertEquals(1, stats1.getElementCountInMemory());
        assertEquals(1, stats1.getHitCount());
        assertEquals(1, stats2.getElementCountInMemory());
        assertEquals(1, stats2.getHitCount());
    } finally {
        cleanup();
    }
}
Also used : Transaction(org.hibernate.Transaction) StaleStateException(org.hibernate.StaleStateException) SecondLevelCacheStatistics(org.hibernate.stat.SecondLevelCacheStatistics) Session(org.hibernate.Session)

Aggregations

StaleStateException (org.hibernate.StaleStateException)4 Session (org.hibernate.Session)3 PersistenceException (javax.persistence.PersistenceException)2 Transaction (org.hibernate.Transaction)2 Test (org.junit.Test)2 SQLException (java.sql.SQLException)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 List (java.util.List)1 Map (java.util.Map)1 Set (java.util.Set)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 CyclicBarrier (java.util.concurrent.CyclicBarrier)1 Future (java.util.concurrent.Future)1 TimeUnit (java.util.concurrent.TimeUnit)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 BiConsumer (java.util.function.BiConsumer)1 EntityExistsException (javax.persistence.EntityExistsException)1 EntityNotFoundException (javax.persistence.EntityNotFoundException)1