Search in sources :

Example 16 with Employee

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

the class CriteriaStringsTest method testSubqueryUncorrelated.

/**
 * Test simple use of a subquery.
 */
public void testSubqueryUncorrelated() {
    EntityManager em = getEM();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        CriteriaBuilder cb = emf.getCriteriaBuilder();
        CriteriaQuery<Employee> crit = cb.createQuery(Employee.class);
        Root<Employee> candidate = crit.from(Employee.class);
        candidate.alias("e");
        crit.select(candidate);
        Path salaryField = candidate.get("salary");
        Subquery<Double> subCrit = crit.subquery(Double.class);
        Root<Employee> subCandidate = subCrit.from(Employee.class);
        subCandidate.alias("e2");
        Path salary2Field = subCandidate.get("salary");
        Subquery<Double> avgSalary = subCrit.select(cb.avg(salary2Field));
        Predicate lessThanAvgSalary = cb.lessThan(salaryField, avgSalary);
        crit.where(lessThanAvgSalary);
        // DN extension
        assertEquals("Generated JPQL query is incorrect", "SELECT AVG(e2.salary) FROM org.datanucleus.samples.annotations.models.company.Employee e2", subCrit.toString());
        // Cannot check on precise query since the subquery name will be a random number
        assertTrue("Main query containing subquery is incorrect", crit.toString().startsWith("SELECT e FROM org.datanucleus.samples.annotations.models.company.Employee e WHERE (e.salary < SUB"));
        Query q = em.createQuery(crit);
        List<Employee> results = q.getResultList();
        assertNotNull("Null results returned!", results);
        assertEquals("Number of results is incorrect", 1, results.size());
        Employee emp = (Employee) results.get(0);
        assertEquals("Employee first name is incorrect", "Joe", emp.getFirstName());
        assertEquals("Employee last name is incorrect", "Bloggs", emp.getLastName());
        tx.rollback();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) Path(javax.persistence.criteria.Path) EntityTransaction(javax.persistence.EntityTransaction) EntityManager(javax.persistence.EntityManager) Employee(org.datanucleus.samples.annotations.models.company.Employee) TypedQuery(javax.persistence.TypedQuery) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) Query(javax.persistence.Query) Predicate(javax.persistence.criteria.Predicate)

Example 17 with Employee

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

the class CriteriaStringsTest method testBasicWithFromJoinOneToOneUsingAttributeName.

/**
 * Test basic generation of query with candidate and alias, and FROM join on 1-1.
 */
public void testBasicWithFromJoinOneToOneUsingAttributeName() {
    EntityManager em = getEM();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        CriteriaBuilder cb = emf.getCriteriaBuilder();
        CriteriaQuery<Employee> crit = cb.createQuery(Employee.class);
        Root<Employee> candidate = crit.from(Employee.class);
        candidate.alias("e");
        crit.select(candidate);
        Join accountJoin = candidate.join("e.account");
        accountJoin.alias("a");
        // DN extension
        assertEquals("Generated JPQL query is incorrect", "SELECT e FROM org.datanucleus.samples.annotations.models.company.Employee e JOIN e.account a", crit.toString());
        Query q = em.createQuery(crit);
        List<Employee> results = q.getResultList();
        assertNotNull("Null results returned!", results);
        assertEquals("Number of results is incorrect", 2, results.size());
        Iterator<Employee> iter = results.iterator();
        boolean joeExists = false;
        boolean nigelExists = false;
        while (iter.hasNext()) {
            Employee emp = iter.next();
            if (emp.getFirstName().equals("Nigel") && emp.getLastName().equals("Bloggs") && emp.getPersonNum() == 106) {
                nigelExists = true;
            } else if (emp.getFirstName().equals("Joe") && emp.getLastName().equals("Bloggs") && emp.getPersonNum() == 105) {
                joeExists = true;
            }
        }
        assertTrue("Nigel not present", nigelExists);
        assertTrue("Joe not present", joeExists);
        tx.rollback();
    } catch (Exception e) {
        LOG.error("Exception thrown during test", e);
        fail("Exception caught during test : " + e.getMessage());
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) EntityTransaction(javax.persistence.EntityTransaction) EntityManager(javax.persistence.EntityManager) Employee(org.datanucleus.samples.annotations.models.company.Employee) TypedQuery(javax.persistence.TypedQuery) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) Query(javax.persistence.Query) Join(javax.persistence.criteria.Join)

Example 18 with Employee

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

the class CriteriaStringsTest method testTREATInWhereClause.

/**
 * Test generation of filter with TREAT.
 */
public void testTREATInWhereClause() {
    EntityManager em = getEM();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        CriteriaBuilder cb = emf.getCriteriaBuilder();
        CriteriaQuery<Qualification> crit = cb.createQuery(Qualification.class);
        Root<Qualification> candidate = crit.from(Qualification.class);
        candidate.alias("q");
        crit.select(candidate);
        Path<Employee> empPath = cb.treat(candidate.get("person"), Employee.class);
        Path agePath = empPath.get("age");
        crit.where(cb.gt(agePath, 40));
        // DN extension
        assertEquals("Generated JPQL query is incorrect", "SELECT q FROM org.datanucleus.samples.annotations.models.company.Qualification q WHERE (TREAT(q.person AS " + Employee.class.getName() + ").age > 40)", crit.toString());
        Query q = em.createQuery(crit);
        List<Qualification> results = q.getResultList();
        assertNotNull("Null results returned!", results);
        assertEquals("Number of results is incorrect", 1, results.size());
        tx.rollback();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) Path(javax.persistence.criteria.Path) EntityTransaction(javax.persistence.EntityTransaction) EntityManager(javax.persistence.EntityManager) Qualification(org.datanucleus.samples.annotations.models.company.Qualification) Employee(org.datanucleus.samples.annotations.models.company.Employee) TypedQuery(javax.persistence.TypedQuery) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) Query(javax.persistence.Query)

Example 19 with Employee

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

the class CriteriaStringsTest method setUp.

/* (non-Javadoc)
     * @see org.datanucleus.tests.PersistenceTestCase#setUp()
     */
@Override
protected void setUp() throws Exception {
    super.setUp();
    EntityManager em = getEM();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        Person p1 = new Person(101, "Fred", "Flintstone", "fred.flintstone@datanucleus.org");
        p1.setAge(35);
        em.persist(p1);
        Person p2 = new Person(102, "Barney", "Rubble", "barney.rubble@datanucleus.org");
        p2.setAge(38);
        p2.setBestFriend(p1);
        em.persist(p2);
        // 1-1 relation sample
        Employee emp1 = new Employee(105, "Joe", "Bloggs", "joe.bloggs@datanucleus.org", 12000.0f, "10005");
        emp1.setAge(40);
        Employee emp2 = new Employee(106, "Nigel", "Bloggs", "nigel.bloggs@datanucleus.org", 13000.0f, "10006");
        emp2.setAge(41);
        Account acc1 = new Account();
        acc1.setId(105);
        acc1.setUsername("joebloggs");
        acc1.setEnabled(true);
        Account acc2 = new Account();
        acc2.setId(106);
        acc2.setUsername("nigelbloggs");
        acc2.setEnabled(true);
        emp1.setAccount(acc1);
        emp2.setAccount(acc2);
        Qualification q1 = new Qualification("BSc");
        Calendar cal = GregorianCalendar.getInstance();
        cal.set(Calendar.YEAR, 2001);
        cal.set(Calendar.MONTH, 5);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        q1.setDate(cal.getTime());
        q1.setPerson(emp1);
        Qualification q2 = new Qualification("MSc");
        q2.setPerson(emp2);
        cal.set(Calendar.YEAR, 2011);
        cal.set(Calendar.MONTH, 4);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        q2.setDate(cal.getTime());
        em.persist(emp1);
        em.persist(emp2);
        em.persist(q1);
        em.persist(q2);
        // 1-N relation sample
        Farm farm1 = new Farm("Giles Farm");
        Farm farm2 = new Farm("Kiwi Farm");
        Animal an1 = new Animal("Brown Cow");
        Animal an2 = new Animal("Woolly Sheep");
        Animal an3 = new Animal("Sheepdog");
        farm1.getAnimals().add(an1);
        an1.setFarm(farm1);
        farm2.getAnimals().add(an2);
        an2.setFarm(farm2);
        farm2.getAnimals().add(an3);
        an3.setFarm(farm2);
        em.persist(farm1);
        em.persist(farm2);
        tx.commit();
    } catch (Exception e) {
        LOG.error(">> Exception in setUp data", e);
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) Account(org.datanucleus.samples.annotations.models.company.Account) EntityManager(javax.persistence.EntityManager) Qualification(org.datanucleus.samples.annotations.models.company.Qualification) Employee(org.datanucleus.samples.annotations.models.company.Employee) Animal(org.datanucleus.samples.annotations.one_many.bidir.Animal) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) Farm(org.datanucleus.samples.annotations.one_many.bidir.Farm) Person(org.datanucleus.samples.annotations.models.company.Person)

Example 20 with Employee

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

the class CriteriaStringsTest method testBasicWithInheritanceInFilter.

/**
 * Test basic generation of query with candidate and alias and filter using field of superclass.
 */
public void testBasicWithInheritanceInFilter() {
    EntityManager em = getEM();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        CriteriaBuilder cb = emf.getCriteriaBuilder();
        CriteriaQuery<Employee> crit = cb.createQuery(Employee.class);
        Root<Employee> candidate = crit.from(Employee.class);
        candidate.alias("e");
        crit.select(candidate);
        Path firstNameField = candidate.get("firstName");
        Predicate firstNameEquals = cb.equal(firstNameField, "Joe");
        crit.where(firstNameEquals);
        // DN extension
        assertEquals("Generated JPQL query is incorrect", "SELECT e FROM org.datanucleus.samples.annotations.models.company.Employee e WHERE" + " (e.firstName = 'Joe')", crit.toString());
        Query q = em.createQuery(crit);
        List<Person> results = q.getResultList();
        assertNotNull("Null results returned!", results);
        assertEquals("Number of results is incorrect", 1, results.size());
        Iterator<Person> iter = results.iterator();
        boolean joePresent = false;
        while (iter.hasNext()) {
            Person pers = iter.next();
            if (pers.getFirstName().equals("Joe") && pers.getLastName().equals("Bloggs") && pers.getPersonNum() == 105) {
                joePresent = true;
            }
        }
        assertTrue("Joe Bloggs was not returned!", joePresent);
        tx.rollback();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) Path(javax.persistence.criteria.Path) EntityTransaction(javax.persistence.EntityTransaction) TypedQuery(javax.persistence.TypedQuery) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) Query(javax.persistence.Query) Predicate(javax.persistence.criteria.Predicate) EntityManager(javax.persistence.EntityManager) Employee(org.datanucleus.samples.annotations.models.company.Employee) Person(org.datanucleus.samples.annotations.models.company.Person)

Aggregations

Employee (org.datanucleus.samples.annotations.models.company.Employee)20 EntityManager (javax.persistence.EntityManager)19 EntityTransaction (javax.persistence.EntityTransaction)19 Query (javax.persistence.Query)11 TypedQuery (javax.persistence.TypedQuery)9 Person (org.datanucleus.samples.annotations.models.company.Person)8 PersistenceException (javax.persistence.PersistenceException)7 Manager (org.datanucleus.samples.annotations.models.company.Manager)7 NoResultException (javax.persistence.NoResultException)6 NonUniqueResultException (javax.persistence.NonUniqueResultException)6 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)6 CriteriaQuery (javax.persistence.criteria.CriteriaQuery)6 ArrayList (java.util.ArrayList)5 List (java.util.List)5 Path (javax.persistence.criteria.Path)4 Predicate (javax.persistence.criteria.Predicate)3 StoreManager (org.datanucleus.store.StoreManager)3 Iterator (java.util.Iterator)2 Join (javax.persistence.criteria.Join)2 Attribute (javax.persistence.metamodel.Attribute)2