Search in sources :

Example 36 with RequiresDialectFeature

use of org.hibernate.testing.RequiresDialectFeature in project hibernate-orm by hibernate.

the class LockTest method testContendedPessimisticWriteLockNoWait.

@Test
@RequiresDialect({ Oracle10gDialect.class, PostgreSQL81Dialect.class })
@RequiresDialectFeature(DialectChecks.SupportsLockTimeouts.class)
public void testContendedPessimisticWriteLockNoWait() throws Exception {
    EntityManager em = getOrCreateEntityManager();
    final EntityManager em2 = createIsolatedEntityManager();
    Lock lock = new Lock();
    Thread t = null;
    FutureTask<Boolean> bgTask;
    final CountDownLatch latch = new CountDownLatch(1);
    try {
        lock.setName("testContendedPessimisticWriteLockNoWait");
        em.getTransaction().begin();
        em.persist(lock);
        em.getTransaction().commit();
        em.clear();
        em.getTransaction().begin();
        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("testContendedPessimisticWriteLockNoWait: got write lock");
        bgTask = new FutureTask<Boolean>(new Callable<Boolean>() {

            public Boolean call() {
                try {
                    // true (success) if LockTimeoutException occurred
                    boolean timedOut = false;
                    em2.getTransaction().begin();
                    log.info("testContendedPessimisticWriteLockNoWait: (BG) about to read write-locked entity");
                    // we should block on the following read
                    Lock lock2 = em2.getReference(Lock.class, id);
                    //  force entity to be read
                    lock2.getName();
                    log.info("testContendedPessimisticWriteLockNoWait: (BG) read write-locked entity");
                    Map<String, Object> props = new HashMap<String, Object>();
                    // timeout of zero means no wait (for lock)
                    props.put(AvailableSettings.LOCK_TIMEOUT, 0);
                    try {
                        em2.lock(lock2, LockModeType.PESSIMISTIC_WRITE, props);
                    } catch (LockTimeoutException e) {
                        // success
                        log.info("testContendedPessimisticWriteLockNoWait: (BG) got expected timeout exception");
                        timedOut = true;
                    } catch (Throwable e) {
                        log.info("Expected LockTimeoutException but got unexpected exception", e);
                    }
                    em2.getTransaction().commit();
                    return timedOut;
                } finally {
                    // signal that we finished
                    latch.countDown();
                }
            }
        });
        t = new Thread(bgTask);
        t.setDaemon(true);
        t.setName("Lock timeout Test (bg)");
        t.start();
        // should return quickly on success
        boolean latchSet = latch.await(10, TimeUnit.SECONDS);
        assertTrue("background test thread finished (lock timeout is broken)", latchSet);
        assertTrue("background test thread timed out on lock attempt", bgTask.get());
        em.getTransaction().commit();
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (t != null) {
            // wait for background thread to finish beforeQuery deleting entity
            t.join();
        }
        em.getTransaction().begin();
        lock = em.getReference(Lock.class, lock.getId());
        em.remove(lock);
        em.getTransaction().commit();
        em.close();
        em2.close();
    }
}
Also used : HashMap(java.util.HashMap) CountDownLatch(java.util.concurrent.CountDownLatch) Callable(java.util.concurrent.Callable) EntityManager(javax.persistence.EntityManager) LockTimeoutException(javax.persistence.LockTimeoutException) Test(org.junit.Test) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature) RequiresDialect(org.hibernate.testing.RequiresDialect)

Example 37 with RequiresDialectFeature

use of org.hibernate.testing.RequiresDialectFeature in project hibernate-orm by hibernate.

the class QueryLockingTest method testEntityLockModeStateAfterQueryLocking.

/**
	 * lock some entities via a query and check the resulting lock mode type via EntityManager
	 */
@Test
@RequiresDialectFeature(value = DialectChecks.DoesNotSupportFollowOnLocking.class)
public void testEntityLockModeStateAfterQueryLocking() {
    // Create some test data
    EntityManager em = getOrCreateEntityManager();
    em.getTransaction().begin();
    em.persist(new LocalEntity(1, "test"));
    em.getTransaction().commit();
    //		em.close();
    // issue the query with locking
    //		em = getOrCreateEntityManager();
    em.getTransaction().begin();
    Query query = em.createQuery("select l from LocalEntity l");
    assertEquals(LockModeType.NONE, query.getLockMode());
    query.setLockMode(LockModeType.PESSIMISTIC_READ);
    assertEquals(LockModeType.PESSIMISTIC_READ, query.getLockMode());
    List<LocalEntity> results = query.getResultList();
    // and check the lock mode for each result
    for (LocalEntity e : results) {
        assertEquals(LockModeType.PESSIMISTIC_READ, em.getLockMode(e));
    }
    em.getTransaction().commit();
    em.close();
    // clean up test data
    em = getOrCreateEntityManager();
    em.getTransaction().begin();
    em.createQuery("delete from LocalEntity").executeUpdate();
    em.getTransaction().commit();
    em.close();
}
Also used : EntityManager(javax.persistence.EntityManager) NativeQuery(org.hibernate.query.NativeQuery) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) Query(javax.persistence.Query) Test(org.junit.Test) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature)

Example 38 with RequiresDialectFeature

use of org.hibernate.testing.RequiresDialectFeature in project hibernate-orm by hibernate.

the class SequenceGeneratorTest method testStartOfSequence.

/**
	 * This seems a little trivial, but we need to guarantee that all Dialects start their sequences on a non-0 value.
	 */
@Test
@TestForIssue(jiraKey = "HHH-8814")
@RequiresDialectFeature(DialectChecks.SupportsSequences.class)
@SkipForDialect(value = SQLServer2012Dialect.class, comment = "SQLServer2012Dialect initializes sequence to minimum value (e.g., Long.MIN_VALUE; Hibernate assumes it is uninitialized.")
public void testStartOfSequence() throws Exception {
    Session s = openSession();
    Transaction tx = s.beginTransaction();
    final Person person = new Person();
    s.persist(person);
    tx.commit();
    s.close();
    assertTrue(person.getId() > 0);
    assertTrue(sqlStatementInterceptor.getSqlQueries().stream().filter(sql -> sql.contains("product_sequence")).findFirst().isPresent());
}
Also used : SkipForDialect(org.hibernate.testing.SkipForDialect) BaseNonConfigCoreFunctionalTestCase(org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature) Session(org.hibernate.Session) SessionFactoryBuilder(org.hibernate.boot.SessionFactoryBuilder) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) SQLServer2012Dialect(org.hibernate.dialect.SQLServer2012Dialect) Transaction(org.hibernate.Transaction) TestForIssue(org.hibernate.testing.TestForIssue) SQLStatementInterceptor(org.hibernate.test.util.jdbc.SQLStatementInterceptor) DialectChecks(org.hibernate.testing.DialectChecks) Map(java.util.Map) Environment(org.hibernate.cfg.Environment) Transaction(org.hibernate.Transaction) Session(org.hibernate.Session) SkipForDialect(org.hibernate.testing.SkipForDialect) Test(org.junit.Test) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature) TestForIssue(org.hibernate.testing.TestForIssue)

Example 39 with RequiresDialectFeature

use of org.hibernate.testing.RequiresDialectFeature in project hibernate-orm by hibernate.

the class ClobLocatorTest method testUnboundedClobLocatorAccess.

@Test
@RequiresDialectFeature(value = DialectChecks.SupportsUnboundedLobLocatorMaterializationCheck.class, comment = "database/driver does not support materializing a LOB locator outside the owning transaction")
public void testUnboundedClobLocatorAccess() throws Throwable {
    // Note: unbounded mutation of the underlying lob data is completely
    // unsupported; most databases would not allow such a construct anyway.
    // Thus here we are only testing materialization...
    String original = buildString(CLOB_SIZE, 'x');
    Session s = openSession();
    s.beginTransaction();
    LobHolder entity = new LobHolder();
    entity.setClobLocator(s.getLobHelper().createClob(original));
    s.save(entity);
    s.getTransaction().commit();
    s.close();
    // load the entity with the clob locator, and close the session/transaction;
    // at that point it is unbounded...
    s = openSession();
    s.beginTransaction();
    entity = s.get(LobHolder.class, entity.getId());
    s.getTransaction().commit();
    s.close();
    assertEquals(CLOB_SIZE, entity.getClobLocator().length());
    assertEquals(original, extractData(entity.getClobLocator()));
    s = openSession();
    s.beginTransaction();
    s.delete(entity);
    s.getTransaction().commit();
    s.close();
}
Also used : Session(org.hibernate.Session) Test(org.junit.Test) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature)

Example 40 with RequiresDialectFeature

use of org.hibernate.testing.RequiresDialectFeature in project hibernate-orm by hibernate.

the class DDLWithoutCallbackTest method testListeners.

@Test
@RequiresDialectFeature(DialectChecks.SupportsColumnCheck.class)
public void testListeners() {
    CupHolder ch = new CupHolder();
    ch.setRadius(new BigDecimal("12"));
    assertDatabaseConstraintViolationThrown(ch);
}
Also used : BigDecimal(java.math.BigDecimal) Test(org.junit.Test) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature)

Aggregations

RequiresDialectFeature (org.hibernate.testing.RequiresDialectFeature)46 Test (org.junit.Test)45 Session (org.hibernate.Session)34 Transaction (org.hibernate.Transaction)17 TestForIssue (org.hibernate.testing.TestForIssue)10 EntityManager (javax.persistence.EntityManager)8 HashMap (java.util.HashMap)7 RequiresDialect (org.hibernate.testing.RequiresDialect)7 List (java.util.List)6 Callable (java.util.concurrent.Callable)6 CountDownLatch (java.util.concurrent.CountDownLatch)6 Query (org.hibernate.Query)6 LockTimeoutException (javax.persistence.LockTimeoutException)5 ArrayList (java.util.ArrayList)4 QuerySyntaxException (org.hibernate.hql.internal.ast.QuerySyntaxException)4 SkipForDialect (org.hibernate.testing.SkipForDialect)4 Query (javax.persistence.Query)3 BigDecimal (java.math.BigDecimal)2 Map (java.util.Map)2 QueryTimeoutException (javax.persistence.QueryTimeoutException)2