Search in sources :

Example 96 with Query

use of javax.persistence.Query in project hibernate-orm by hibernate.

the class QueryHintEntityGraphTest method testEntityGraphWithCollectionSubquery.

@Test
@TestForIssue(jiraKey = "HHH-9374")
public void testEntityGraphWithCollectionSubquery() {
    EntityManager entityManager = getOrCreateEntityManager();
    entityManager.getTransaction().begin();
    EntityGraph<Company> entityGraph = entityManager.createEntityGraph(Company.class);
    entityGraph.addAttributeNodes("location");
    Query query = entityManager.createQuery("select c from " + Company.class.getName() + " c where c.employees IS EMPTY");
    query.setHint(QueryHints.HINT_LOADGRAPH, entityGraph);
    query.getResultList();
    entityManager.getTransaction().commit();
    entityManager.close();
}
Also used : EntityManager(javax.persistence.EntityManager) Company(org.hibernate.jpa.test.graphs.Company) Query(javax.persistence.Query) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 97 with Query

use of javax.persistence.Query in project hibernate-orm by hibernate.

the class LockTest method testQueryTimeoutEMProps.

@Test
@RequiresDialect(Oracle10gDialect.class)
@RequiresDialectFeature(DialectChecks.SupportsLockTimeouts.class)
@FailureExpected(jiraKey = "HHH-8001")
public void testQueryTimeoutEMProps() throws Exception {
    EntityManager em = getOrCreateEntityManager();
    Map<String, Object> queryTimeoutProps = new HashMap<String, Object>();
    // 1 sec timeout (should round up)
    queryTimeoutProps.put(QueryHints.SPEC_HINT_TIMEOUT, 500);
    final EntityManager em2 = createIsolatedEntityManager(queryTimeoutProps);
    Lock lock = new Lock();
    Thread t = null;
    FutureTask<Boolean> bgTask;
    final CountDownLatch latch = new CountDownLatch(1);
    try {
        lock.setName("testQueryTimeout");
        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("testQueryTimeout: 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("testQueryTimeout: (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("testQueryTimeout: (BG) read write-locked entity");
                    try {
                        // we should block on the following read
                        Query query = em2.createQuery("select L from Lock_ L where L.id < 10000 ");
                        query.setLockMode(LockModeType.PESSIMISTIC_READ);
                        List<Lock> resultList = query.getResultList();
                        //  force entity to be read
                        String name = resultList.get(0).getName();
                        log.info("testQueryTimeout: name read =" + name);
                    } catch (QueryTimeoutException e) {
                        // success
                        log.info("testQueryTimeout: (BG) got expected timeout exception");
                        timedOut = true;
                    } catch (Throwable e) {
                        log.info("testQueryTimeout: 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("testQueryTimeout (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 : Query(javax.persistence.Query) HashMap(java.util.HashMap) CountDownLatch(java.util.concurrent.CountDownLatch) Callable(java.util.concurrent.Callable) QueryTimeoutException(javax.persistence.QueryTimeoutException) EntityManager(javax.persistence.EntityManager) Test(org.junit.Test) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature) FailureExpected(org.hibernate.testing.FailureExpected) RequiresDialect(org.hibernate.testing.RequiresDialect)

Example 98 with Query

use of javax.persistence.Query in project hibernate-orm by hibernate.

the class LockTimeoutPropertyTest method testTimeoutHint.

@Test
@TestForIssue(jiraKey = "HHH-6256")
public void testTimeoutHint() {
    EntityManager em = getOrCreateEntityManager();
    em.getTransaction().begin();
    boolean b = em.getProperties().containsKey(AvailableSettings.LOCK_TIMEOUT);
    assertTrue(b);
    int timeout = Integer.valueOf(em.getProperties().get(AvailableSettings.LOCK_TIMEOUT).toString());
    assertEquals(2000, timeout);
    org.hibernate.query.Query q = (org.hibernate.query.Query) em.createQuery("select u from UnversionedLock u");
    timeout = q.getLockOptions().getTimeOut();
    assertEquals(2000, timeout);
    Query query = em.createQuery("select u from UnversionedLock u");
    query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    query.setHint(AvailableSettings.LOCK_TIMEOUT, 3000);
    q = (org.hibernate.query.Query) query;
    timeout = q.getLockOptions().getTimeOut();
    assertEquals(3000, timeout);
    em.getTransaction().rollback();
    em.close();
}
Also used : EntityManager(javax.persistence.EntityManager) Query(javax.persistence.Query) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 99 with Query

use of javax.persistence.Query in project hibernate-orm by hibernate.

the class QueryLockingTest method testNoneLockModeForNonSelectQueryAllowed.

@Test
@TestForIssue(jiraKey = "HHH-8756")
public void testNoneLockModeForNonSelectQueryAllowed() {
    EntityManager em = getOrCreateEntityManager();
    em.getTransaction().begin();
    org.hibernate.query.Query query = em.createQuery("delete from Lockable l").unwrap(org.hibernate.query.Query.class);
    assertEquals(LockMode.NONE, query.getLockOptions().getLockMode());
    query.setLockMode(LockModeType.NONE);
    em.getTransaction().commit();
    em.clear();
    // ensure other modes still throw the exception
    em.getTransaction().begin();
    query = em.createQuery("delete from Lockable l").unwrap(org.hibernate.query.Query.class);
    assertEquals(LockMode.NONE, query.getLockOptions().getLockMode());
    try {
        // Throws IllegalStateException
        query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
        fail("IllegalStateException should have been thrown.");
    } catch (IllegalStateException e) {
    // expected
    } finally {
        em.getTransaction().rollback();
        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) TestForIssue(org.hibernate.testing.TestForIssue)

Example 100 with Query

use of javax.persistence.Query in project hibernate-orm by hibernate.

the class AddNamedQueryTest method testFlushModeHandling.

@Test
public void testFlushModeHandling() {
    final String name = "flush-mode-handling";
    EntityManager em = getOrCreateEntityManager();
    em.getTransaction().begin();
    Query q = em.createQuery("from Item");
    assertEquals(FlushModeType.AUTO, q.getFlushMode());
    q.setFlushMode(FlushModeType.COMMIT);
    assertEquals(FlushModeType.COMMIT, q.getFlushMode());
    em.getEntityManagerFactory().addNamedQuery(name, q);
    // first, lets check the underlying stored query def
    SessionFactoryImplementor sfi = entityManagerFactory().unwrap(SessionFactoryImplementor.class);
    NamedQueryDefinition def = sfi.getNamedQueryRepository().getNamedQueryDefinition(name);
    assertEquals(FlushMode.COMMIT, def.getFlushMode());
    // then lets create a query by name and check its setting
    q = em.createNamedQuery(name);
    assertEquals(FlushMode.COMMIT, q.unwrap(org.hibernate.Query.class).getHibernateFlushMode());
    assertEquals(FlushModeType.COMMIT, q.getFlushMode());
    em.getTransaction().commit();
    em.close();
}
Also used : EntityManager(javax.persistence.EntityManager) Query(javax.persistence.Query) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) NamedQueryDefinition(org.hibernate.engine.spi.NamedQueryDefinition) Test(org.junit.Test)

Aggregations

Query (javax.persistence.Query)747 EntityManager (javax.persistence.EntityManager)203 Transactional (org.springframework.transaction.annotation.Transactional)160 TypedQuery (javax.persistence.TypedQuery)159 NoResultException (javax.persistence.NoResultException)152 Test (org.junit.Test)119 CriteriaQuery (javax.persistence.criteria.CriteriaQuery)92 List (java.util.List)72 ArrayList (java.util.ArrayList)51 BigInteger (java.math.BigInteger)30 ConfigurationStoreException (org.nhindirect.config.store.ConfigurationStoreException)21 Item (org.hibernate.jpa.test.Item)19 PersistenceException (javax.persistence.PersistenceException)17 NonUniqueResultException (javax.persistence.NonUniqueResultException)14 TestForIssue (org.hibernate.testing.TestForIssue)14 DomainDao (org.nhindirect.config.store.dao.DomainDao)14 NamedQuery (javax.persistence.NamedQuery)12 SkipForDialect (org.hibernate.testing.SkipForDialect)11 Domain (org.nhindirect.config.store.Domain)10 TblModuleManifest (com.intel.mtwilson.as.data.TblModuleManifest)9