Search in sources :

Example 6 with TransactionException

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

the class AbstractLogicalConnectionImplementor method rollback.

@Override
public void rollback() {
    try {
        log.trace("Preparing to rollback transaction via JDBC Connection.rollback()");
        getConnectionForTransactionManagement().rollback();
        status = TransactionStatus.ROLLED_BACK;
        log.trace("Transaction rolled-back via JDBC Connection.rollback()");
    } catch (SQLException e) {
        status = TransactionStatus.FAILED_ROLLBACK;
        throw new TransactionException("Unable to rollback against JDBC Connection", e);
    }
    afterCompletion();
}
Also used : TransactionException(org.hibernate.TransactionException) SQLException(java.sql.SQLException)

Example 7 with TransactionException

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

the class LockTest method testContendedPessimisticLock.

@Test
@SkipForDialect(HSQLDialect.class)
// only.
@SkipForDialect(value = { SybaseASE15Dialect.class }, strictMatching = true, jiraKey = "HHH-6820")
@SkipForDialect(value = { SQLServerDialect.class })
public void testContendedPessimisticLock() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final Lock lock = new Lock();
    FutureTask<Boolean> bgTask = new FutureTask<>(() -> {
        AtomicBoolean backgroundThreadHasReadNewValue = new AtomicBoolean();
        try {
            doInJPA(this::entityManagerFactory, _entityManager -> {
                TransactionUtil.setJdbcTimeout(_entityManager.unwrap(Session.class));
                log.info("testContendedPessimisticLock: (BG) about to issue (PESSIMISTIC_READ) query against 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();
                    Lock _lock = resultList.get(0);
                    backgroundThreadHasReadNewValue.set(_lock.getName().equals("foo"));
                } catch (RuntimeException e) {
                    if (!ExceptionUtil.isSqlLockTimeout(e)) {
                        fail("An error occurred waiting while attempting to read the entity: " + e.getMessage());
                    }
                    backgroundThreadHasReadNewValue.set(false);
                }
            });
        } catch (TransactionException e) {
            if (!ExceptionUtil.isConnectionClose(e)) {
                fail("Unexpected exception: " + e.getMessage());
            }
        } finally {
            // signal that we finished
            latch.countDown();
        }
        return backgroundThreadHasReadNewValue.get();
    });
    Thread t = new Thread(bgTask);
    t.setDaemon(true);
    t.setName("Lock timeout Test (bg)");
    try {
        lock.setName("testContendedPessimisticLock");
        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);
            // modify and flush, but don't commit the transaction
            _lock.setName("foo");
            em.flush();
            log.info("testContendedPessimisticLock: got write lock");
            try {
                t.start();
                // should return quickly on success
                boolean backGroundThreadCompleted = latch.await(10, TimeUnit.SECONDS);
                if (backGroundThreadCompleted) {
                    // the background thread read a value. At the very least we need to assert that he did not see the
                    // changed value
                    boolean backgroundThreadHasReadNewValue = bgTask.get();
                    assertFalse("The background thread is not allowed to see the updated value while the first transaction has not committed yet", backgroundThreadHasReadNewValue);
                } else {
                    log.debug("The background thread was blocked");
                    boolean backgroundThreadHasReadNewValue = bgTask.get();
                    assertTrue("Background thread should read the new value after being unblocked", backgroundThreadHasReadNewValue);
                }
            } catch (InterruptedException e) {
                Thread.interrupted();
            } catch (ExecutionException e) {
                fail(e.getMessage());
            }
        });
    } finally {
        // wait for background thread to finish before deleting entity
        t.join();
        doInJPA(this::entityManagerFactory, em -> {
            Lock _lock = em.getReference(Lock.class, lock.getId());
            em.remove(_lock);
        });
    }
}
Also used : Query(javax.persistence.Query) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TransactionException(org.hibernate.TransactionException) FutureTask(java.util.concurrent.FutureTask) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ExecutionException(java.util.concurrent.ExecutionException) Session(org.hibernate.Session) SkipForDialect(org.hibernate.testing.SkipForDialect) Test(org.junit.Test)

Example 8 with TransactionException

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

the class AbstractLogicalConnectionImplementor method commit.

@Override
public void commit() {
    try {
        log.trace("Preparing to commit transaction via JDBC Connection.commit()");
        getConnectionForTransactionManagement().commit();
        status = TransactionStatus.COMMITTED;
        log.trace("Transaction committed via JDBC Connection.commit()");
    } catch (SQLException e) {
        status = TransactionStatus.FAILED_COMMIT;
        throw new TransactionException("Unable to commit against JDBC Connection", e);
    }
    afterCompletion();
}
Also used : TransactionException(org.hibernate.TransactionException) SQLException(java.sql.SQLException)

Example 9 with TransactionException

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

the class JtaTransactionAdapterTransactionManagerImpl method begin.

@Override
public void begin() {
    try {
        if (getStatus() == TransactionStatus.NOT_ACTIVE) {
            log.trace("Calling TransactionManager#begin");
            transactionManager.begin();
            initiator = true;
            log.trace("Called TransactionManager#begin");
        } else {
            log.trace("Skipping TransactionManager#begin due to already active transaction");
        }
    } catch (Exception e) {
        throw new TransactionException("JTA TransactionManager#begin failed", e);
    }
}
Also used : TransactionException(org.hibernate.TransactionException) SystemException(javax.transaction.SystemException) TransactionException(org.hibernate.TransactionException)

Example 10 with TransactionException

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

the class JtaTransactionAdapterTransactionManagerImpl method commit.

@Override
public void commit() {
    try {
        if (initiator) {
            initiator = false;
            log.trace("Calling TransactionManager#commit");
            transactionManager.commit();
            log.trace("Called TransactionManager#commit");
        } else {
            log.trace("Skipping TransactionManager#commit due to not being initiator");
        }
    } catch (Exception e) {
        throw new TransactionException("JTA TransactionManager#commit failed", e);
    }
}
Also used : TransactionException(org.hibernate.TransactionException) SystemException(javax.transaction.SystemException) TransactionException(org.hibernate.TransactionException)

Aggregations

TransactionException (org.hibernate.TransactionException)16 SystemException (javax.transaction.SystemException)6 Test (org.junit.Test)5 Session (org.hibernate.Session)4 SQLException (java.sql.SQLException)3 Transaction (org.hibernate.Transaction)2 SessionImplementor (org.hibernate.engine.spi.SessionImplementor)2 CountDownLatch (java.util.concurrent.CountDownLatch)1 ExecutionException (java.util.concurrent.ExecutionException)1 FutureTask (java.util.concurrent.FutureTask)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 PersistenceException (javax.persistence.PersistenceException)1 Query (javax.persistence.Query)1 TransactionManager (javax.transaction.TransactionManager)1 AssertionFailure (org.hibernate.AssertionFailure)1 EmptyInterceptor (org.hibernate.EmptyInterceptor)1 Interceptor (org.hibernate.Interceptor)1 LazyInitializationException (org.hibernate.LazyInitializationException)1 BeforeTransactionCompletionProcess (org.hibernate.action.spi.BeforeTransactionCompletionProcess)1 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)1