Search in sources :

Example 1 with Organisation

use of org.datanucleus.samples.annotations.models.company.Organisation in project tests by datanucleus.

the class JPQLSubqueryTest method testHavingSubquery.

/**
 * Simple query using a subquery in the HAVING clause.
 */
public void testHavingSubquery() {
    if (!(storeMgr instanceof RDBMSStoreManager)) {
        return;
    }
    DatastoreAdapter dba = ((RDBMSStoreManager) storeMgr).getDatastoreAdapter();
    if (!dba.supportsOption(DatastoreAdapter.SUBQUERY_IN_HAVING)) {
        return;
    }
    try {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            Account a1 = new Account();
            a1.setUsername("Flintstone");
            a1.setId(1);
            em.persist(a1);
            Organisation o1 = new Organisation("Flintstone");
            o1.setDescription("Freds organisation");
            em.persist(o1);
            // TODO Come up with a better sample query. Why does the JPA TCK/Spec have none?
            List<Person> result = em.createQuery("SELECT o FROM " + Organisation.class.getName() + " o " + "GROUP BY o.name HAVING EXISTS (SELECT a FROM " + Account.class.getName() + " a WHERE a.username = o.name)").getResultList();
            assertNotNull(result);
            assertEquals(1, result.size());
            tx.rollback();
        } catch (Exception e) {
            LOG.error("Exception in query", e);
            fail("Exception executing query with HAVING subquery : " + e.getMessage());
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            em.close();
        }
    } finally {
        clean(Person.class);
    }
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) Account(org.datanucleus.samples.annotations.models.company.Account) EntityManager(javax.persistence.EntityManager) Organisation(org.datanucleus.samples.annotations.models.company.Organisation) DatastoreAdapter(org.datanucleus.store.rdbms.adapter.DatastoreAdapter) Person(org.datanucleus.samples.annotations.models.company.Person) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager)

Aggregations

EntityManager (javax.persistence.EntityManager)1 EntityTransaction (javax.persistence.EntityTransaction)1 Account (org.datanucleus.samples.annotations.models.company.Account)1 Organisation (org.datanucleus.samples.annotations.models.company.Organisation)1 Person (org.datanucleus.samples.annotations.models.company.Person)1 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)1 DatastoreAdapter (org.datanucleus.store.rdbms.adapter.DatastoreAdapter)1