Search in sources :

Example 1 with Employee

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

the class JPQLQueryTest method removeManagerEmployeeRelation.

private void removeManagerEmployeeRelation() {
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        Query q = em.createQuery("SELECT m FROM " + Manager.class.getName() + " m");
        List<Manager> managers = q.getResultList();
        for (Manager m : managers) {
            Set<Employee> emps = m.getSubordinates();
            for (Employee e : emps) {
                e.setManager(null);
            }
            m.clearSubordinates();
        }
        tx.commit();
    } catch (Exception e) {
        LOG.error("Exception performing removal of Manager-Employee relation", e);
        fail("Error in cleanup : " + e.getMessage());
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
    emf.getCache().evictAll();
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) EntityManager(javax.persistence.EntityManager) Employee(org.datanucleus.samples.annotations.models.company.Employee) JPAQuery(org.datanucleus.api.jpa.JPAQuery) Query(javax.persistence.Query) TypedQuery(javax.persistence.TypedQuery) StoreManager(org.datanucleus.store.StoreManager) Manager(org.datanucleus.samples.annotations.models.company.Manager) EntityManager(javax.persistence.EntityManager) NoResultException(javax.persistence.NoResultException) NonUniqueResultException(javax.persistence.NonUniqueResultException) PersistenceException(javax.persistence.PersistenceException)

Example 2 with Employee

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

the class JPQLQueryTest method testTYPE.

public void testTYPE() {
    try {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            Person p = new Person(101, "Fred", "Flintstone", "fred.flintstone@jpox.com");
            em.persist(p);
            Employee e = new Employee(102, "Barney", "Rubble", "barney.rubble@jpox.com", 10000.0f, "12345");
            em.persist(e);
            em.flush();
            List<Person> result = em.createQuery("SELECT p FROM " + Person.class.getName() + " p WHERE TYPE(p) <> Employee_Ann").getResultList();
            assertEquals(1, result.size());
            Person p1 = result.get(0);
            assertTrue(p1 instanceof Person && !(p1 instanceof Employee));
            List result2 = em.createQuery("SELECT p FROM " + Person.class.getName() + " p WHERE TYPE(p) IN (Employee_Ann, Person_Ann)").getResultList();
            assertEquals(2, result2.size());
            List<Person> result3 = em.createQuery("SELECT p FROM " + Person.class.getName() + " p WHERE TYPE(p) IN (Employee_Ann)").getResultList();
            assertEquals(1, result3.size());
            Person p3 = result3.get(0);
            assertTrue(p3 instanceof Employee);
            List<Person> result4 = em.createQuery("SELECT p FROM " + Person.class.getName() + " p WHERE TYPE(p) NOT IN (Employee_Ann)").getResultList();
            assertEquals(1, result4.size());
            Person p4 = result4.get(0);
            assertTrue(p4 instanceof Person && !(p4 instanceof Employee));
            Collection<String> collParam = new ArrayList<>();
            collParam.add("Employee_Ann");
            collParam.add("Person_Ann");
            TypedQuery<Person> q5 = (TypedQuery<Person>) em.createQuery("SELECT p FROM " + Person.class.getName() + " p WHERE TYPE(p) IN :collParam");
            q5.setParameter("collParam", collParam);
            List<Person> result5 = q5.getResultList();
            assertEquals(2, result5.size());
            Collection<Class> collParam2 = new ArrayList<>();
            collParam2.add(Employee.class);
            collParam2.add(Person.class);
            TypedQuery<Person> q6 = (TypedQuery<Person>) em.createQuery("SELECT p FROM " + Person.class.getName() + " p WHERE TYPE(p) IN :collParam");
            q6.setParameter("collParam", collParam2);
            List<Person> result6 = q6.getResultList();
            assertEquals(2, result6.size());
            // Test for TYPE using a discriminator sample
            User u = new User(1, "Basic User");
            em.persist(u);
            SuperUser su = new SuperUser(2, "Root", "Admin");
            em.persist(su);
            em.flush();
            List<Object[]> result7 = em.createQuery("SELECT u.name, TYPE(u) FROM " + User.class.getName() + " u ORDER BY u.id").getResultList();
            assertEquals(2, result7.size());
            Object[] result7_0 = result7.get(0);
            Object[] result7_1 = result7.get(1);
            assertEquals(2, result7_0.length);
            assertEquals("Basic User", result7_0[0]);
            assertEquals("User", result7_0[1]);
            assertEquals("Root", result7_1[0]);
            assertEquals("SuperUser", result7_1[1]);
            tx.rollback();
        } catch (Exception e) {
            LOG.error("Exception in query", e);
            fail("Exception in TYPE handling : " + e.getMessage());
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            em.close();
        }
    } finally {
        clean(Employee.class);
        clean(Person.class);
    }
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) User(org.datanucleus.samples.annotations.inherited.User) SuperUser(org.datanucleus.samples.annotations.inherited.SuperUser) TypedQuery(javax.persistence.TypedQuery) ArrayList(java.util.ArrayList) NoResultException(javax.persistence.NoResultException) NonUniqueResultException(javax.persistence.NonUniqueResultException) PersistenceException(javax.persistence.PersistenceException) EntityManager(javax.persistence.EntityManager) Employee(org.datanucleus.samples.annotations.models.company.Employee) List(java.util.List) ArrayList(java.util.ArrayList) Person(org.datanucleus.samples.annotations.models.company.Person) SuperUser(org.datanucleus.samples.annotations.inherited.SuperUser)

Example 3 with Employee

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

the class JPQLUpdateTest method testBulkUpdateUsingWhereSubquery.

/**
 * Test of bulk UPDATE statement with a subquery in the WHERE clause.
 */
public void testBulkUpdateUsingWhereSubquery() {
    if (!storeMgr.getSupportedOptions().contains(StoreManager.OPTION_QUERY_JPQL_BULK_UPDATE)) {
        return;
    }
    if (vendorID != null && vendorID.equalsIgnoreCase("mysql")) {
        // MySQL has issues with using subqueries in UPDATE statements
        return;
    }
    try {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            Employee e1 = new Employee(101, "Fred", "Flintstone", "fred.flintstone@jpox.com", 10000f, "12001");
            e1.setAge(35);
            em.persist(e1);
            Employee e2 = new Employee(101, "Fred", "Flintstone", "fred.flintstone@jpox.com", 20000f, "12000");
            e2.setAge(45);
            em.persist(e2);
            em.flush();
            Query q = em.createQuery("UPDATE Employee_Ann e SET e.salary = e.salary+:param WHERE e.age > (SELECT AVG(emp.age) FROM Employee_Ann emp)");
            q.setParameter("param", 100);
            int val = q.executeUpdate();
            assertEquals("Number of records updated by query was incorrect", 1, val);
            tx.commit();
        // TODO Check the datastore contents
        } catch (Throwable e) {
            LOG.error("Exception thrown in bulk update", e);
            fail("Exception thrown on bulk update : " + e.getMessage());
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            em.close();
        }
    } finally {
        clean(Employee.class);
    }
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) EntityManager(javax.persistence.EntityManager) Employee(org.datanucleus.samples.annotations.models.company.Employee) Query(javax.persistence.Query)

Example 4 with Employee

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

the class CriteriaStringsTest method testSubqueryExists.

/**
 * Test use of an EXISTS subquery.
 */
public void testSubqueryExists() {
    EntityManager em = getEM();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        CriteriaBuilder cb = emf.getCriteriaBuilder();
        CriteriaQuery<Person> crit = cb.createQuery(Person.class);
        Root<Person> candidate = crit.from(Person.class);
        candidate.alias("p");
        crit.select(candidate);
        Subquery<Person> subCrit = crit.subquery(Person.class);
        Root<Person> subCandidate = subCrit.from(Person.class);
        subCandidate.alias("p2");
        subCrit.select(subCandidate);
        Path bestFriendField = subCandidate.get("bestFriend");
        Predicate bestFriendEqual = cb.equal(bestFriendField, candidate);
        subCrit.where(bestFriendEqual);
        Predicate existsBestFriend = cb.exists(subCrit);
        crit.where(existsBestFriend);
        // DN extension
        assertEquals("Generated JPQL query is incorrect", "SELECT p2 FROM org.datanucleus.samples.annotations.models.company.Person p2 WHERE (p2.bestFriend = p)", 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 p FROM org.datanucleus.samples.annotations.models.company.Person p WHERE EXISTS "));
        Query q = em.createQuery(crit);
        List<Employee> results = q.getResultList();
        assertNotNull("Null results returned!", results);
        assertEquals("Number of results is incorrect", 1, results.size());
        Person p = (Person) results.get(0);
        assertEquals("Employee first name is incorrect", "Fred", p.getFirstName());
        assertEquals("Employee last name is incorrect", "Flintstone", p.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) Person(org.datanucleus.samples.annotations.models.company.Person) Predicate(javax.persistence.criteria.Predicate)

Example 5 with Employee

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

the class CriteriaStringsTest method testBasicWithFromJoinOneToOne.

/**
 * Test basic generation of query with candidate and alias, and FROM join on 1-1.
 */
public void testBasicWithFromJoinOneToOne() {
    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);
        Metamodel model = emf.getMetamodel();
        ManagedType empType = model.managedType(Employee.class);
        Attribute bAttr = empType.getAttribute("account");
        Join accountJoin = candidate.join((SingularAttribute) bAttr);
        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();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) EntityTransaction(javax.persistence.EntityTransaction) ManagedType(javax.persistence.metamodel.ManagedType) TypedQuery(javax.persistence.TypedQuery) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) Query(javax.persistence.Query) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Attribute(javax.persistence.metamodel.Attribute) ListAttribute(javax.persistence.metamodel.ListAttribute) Join(javax.persistence.criteria.Join) EntityManager(javax.persistence.EntityManager) Employee(org.datanucleus.samples.annotations.models.company.Employee) Metamodel(javax.persistence.metamodel.Metamodel)

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