use of javax.persistence.PessimisticLockException in project hibernate-orm by hibernate.
the class LockTest method testFindWithPessimisticWriteLockTimeoutException.
//5 minutes
@Test(timeout = 5 * 60 * 1000)
@TestForIssue(jiraKey = "HHH-7252")
@RequiresDialectFeature(value = DialectChecks.SupportsLockTimeouts.class, comment = "Test verifies proper exception throwing when a lock timeout is specified.", jiraKey = "HHH-7252")
public void testFindWithPessimisticWriteLockTimeoutException() {
Lock lock = new Lock();
lock.setName("name");
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist(lock);
em.getTransaction().commit();
em.close();
EntityManager em2 = createIsolatedEntityManager();
em2.getTransaction().begin();
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(AvailableSettings.LOCK_TIMEOUT, 0L);
Lock lock2 = em2.find(Lock.class, lock.getId(), LockModeType.PESSIMISTIC_WRITE, properties);
assertEquals("lock mode should be PESSIMISTIC_WRITE ", LockModeType.PESSIMISTIC_WRITE, em2.getLockMode(lock2));
EntityManager em3 = createIsolatedEntityManager();
em3.getTransaction().begin();
try {
em3.find(Lock.class, lock.getId(), LockModeType.PESSIMISTIC_WRITE, properties);
fail("Exception should be thrown");
} catch (LockTimeoutException lte) {
// Proper exception thrown for dialect supporting lock timeouts when an immediate timeout is set.
} catch (PessimisticLockException pe) {
fail("Find with immediate timeout should have thrown LockTimeoutException.");
} catch (PersistenceException pe) {
log.info("EntityManager.find() for PESSIMISTIC_WRITE with timeout of 0 threw a PersistenceException.\n" + "This is likely a consequence of " + getDialect().getClass().getName() + " not properly mapping SQL errors into the correct HibernateException subtypes.\n" + "See HHH-7251 for an example of one such situation.", pe);
fail("EntityManager should be throwing LockTimeoutException.");
} finally {
if (em3.getTransaction().getRollbackOnly()) {
em3.getTransaction().rollback();
} else {
em3.getTransaction().commit();
}
em3.close();
}
em2.getTransaction().commit();
em2.getTransaction().begin();
em2.remove(lock2);
em2.getTransaction().commit();
em2.close();
}
use of javax.persistence.PessimisticLockException 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;
}
use of javax.persistence.PessimisticLockException in project microservices by pwillhan.
the class Locking method pessimisticReadWrite.
@Test
public void pessimisticReadWrite() throws Exception {
final ConcurrencyTestData testData = storeCategoriesAndItems();
Long[] CATEGORIES = testData.categories.identifiers;
UserTransaction tx = TM.getUserTransaction();
try {
tx.begin();
EntityManager em = JPA.createEntityManager();
BigDecimal totalPrice = new BigDecimal(0);
for (Long categoryId : CATEGORIES) {
/*
For each <code>Category</code>, query all <code>Item</code> instances in
<code>PESSIMISTIC_READ</code> lock mode. Hibernate will lock the rows in
the database with the SQL query. If possible, wait for 5 seconds if some
other transaction already holds a conflicting lock. If the lock can't
be obtained, the query throws an exception.
*/
List<Item> items = em.createQuery("select i from Item i where i.category.id = :catId").setLockMode(LockModeType.PESSIMISTIC_READ).setHint("javax.persistence.lock.timeout", 5000).setParameter("catId", categoryId).getResultList();
/*
If the query returns successfully, you know that you hold an exclusive lock
on the data and no other transaction can access it with an exclusive lock or
modify it until this transaction commits.
*/
for (Item item : items) totalPrice = totalPrice.add(item.getBuyNowPrice());
// read or write locks, only exclusive locks.
if (categoryId.equals(testData.categories.getFirstId())) {
Executors.newSingleThreadExecutor().submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
UserTransaction tx = TM.getUserTransaction();
try {
tx.begin();
EntityManager em = JPA.createEntityManager();
// connection/session.
if (TM.databaseProduct.equals(DatabaseProduct.POSTGRESQL)) {
em.unwrap(Session.class).doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
connection.createStatement().execute("set statement_timeout = 5000");
}
});
}
// can set a timeout for the whole connection/session.
if (TM.databaseProduct.equals(DatabaseProduct.MYSQL)) {
em.unwrap(Session.class).doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
connection.createStatement().execute("set innodb_lock_wait_timeout = 5;");
}
});
}
// Moving the first item from the first category into the last category
// This query should fail as someone else holds a lock on the rows.
List<Item> items = em.createQuery("select i from Item i where i.category.id = :catId").setParameter("catId", testData.categories.getFirstId()).setLockMode(// Prevent concurrent access
LockModeType.PESSIMISTIC_WRITE).setHint("javax.persistence.lock.timeout", // Only works on Oracle...
5000).getResultList();
Category lastCategory = em.getReference(Category.class, testData.categories.getLastId());
items.iterator().next().setCategory(lastCategory);
tx.commit();
em.close();
} catch (Exception ex) {
// This should fail, as the data is already locked!
TM.rollback();
if (TM.databaseProduct.equals(DatabaseProduct.POSTGRESQL)) {
// A statement timeout on PostgreSQL doesn't produce a specific exception
assertTrue(ex instanceof PersistenceException);
} else if (TM.databaseProduct.equals(DatabaseProduct.MYSQL)) {
// On MySQL we get a LockTimeoutException
assertTrue(ex instanceof LockTimeoutException);
} else {
// On H2 and Oracle we get a PessimisticLockException
assertTrue(ex instanceof PessimisticLockException);
}
}
return null;
}
}).get();
}
}
/*
Our locks will be released after commit, when the transaction completes.
*/
tx.commit();
em.close();
assertEquals(totalPrice.compareTo(new BigDecimal("108")), 0);
} finally {
TM.rollback();
}
}
use of javax.persistence.PessimisticLockException in project oozie by apache.
the class TestPersistenceExceptionSubclassFilterRetryPredicate method testNestedFilteredJPAExceptions.
@Test
public void testNestedFilteredJPAExceptions() {
assertFalse(predicate.apply(wrapCause(new EntityExistsException())));
assertFalse(predicate.apply(wrapCause(new EntityNotFoundException())));
assertFalse(predicate.apply(wrapCause(new LockTimeoutException())));
assertFalse(predicate.apply(wrapCause(new NoResultException())));
assertFalse(predicate.apply(wrapCause(new NonUniqueResultException())));
assertFalse(predicate.apply(wrapCause(new OptimisticLockException())));
assertFalse(predicate.apply(wrapCause(new PessimisticLockException())));
assertFalse(predicate.apply(wrapCause(new QueryTimeoutException())));
assertFalse(predicate.apply(wrapCause(new TransactionRequiredException())));
}
use of javax.persistence.PessimisticLockException in project cuba by cuba-platform.
the class DbBasedCoordinator method getTasks.
protected synchronized List<ScheduledTask> getTasks() {
log.trace("Read all active tasks from DB and lock them");
EntityManager em = persistence.getEntityManager();
try {
// noinspection unchecked
return em.createQuery("select t from sys$ScheduledTask t where t.active = true").setLockMode(LockModeType.PESSIMISTIC_WRITE).getResultList();
} catch (PessimisticLockException e) {
log.info("Unable to acquire lock on tasks");
if (log.isTraceEnabled()) {
log.trace("Unable to acquire lock on tasks. Error:", e);
}
throw new SchedulingLockException("Lock exception while acquiring tasks");
}
}
Aggregations