Search in sources :

Example 96 with Employee

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

the class JDOQLEvaluatorTest method testFilterInstanceOf.

/**
 * Test of filter with "instanceof".
 */
public void testFilterInstanceOf() {
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();
        // Create some instances to query over
        List<Person> instances = new ArrayList<>();
        Person p1 = new Person(101, "Mickey", "Mouse", "mickey.mouse@warnerbros.com");
        p1.setAge(34);
        Employee p2 = new Employee(102, "Donald", "Duck", "donald.duck@warnerbros.com", 13400.0f, "12345");
        p2.setAge(38);
        Person p3 = new Person(103, "Minnie", "Mouse", "minnie.mouse@warnerbros.com");
        p3.setAge(31);
        instances.add(p1);
        instances.add(p2);
        instances.add(p3);
        // Compile the query
        JDOQuery q = (JDOQuery) pm.newQuery(Person.class, "this instanceof " + Employee.class.getName());
        Query query = q.getInternalQuery();
        ClassLoaderResolver clr = query.getExecutionContext().getClassLoaderResolver();
        JavaQueryCompiler compiler = new JDOQLCompiler(query.getExecutionContext().getNucleusContext(), clr, null, query.getCandidateClass(), null, query.getFilter(), query.getParsedImports(), query.getOrdering(), query.getResult(), query.getGrouping(), query.getHaving(), query.getExplicitParametersDeclaration(), query.getExplicitVariablesDeclaration(), null);
        QueryCompilation compilation = compiler.compile(new HashMap(), null);
        // Execute the query
        JavaQueryInMemoryEvaluator eval = new JDOQLInMemoryEvaluator(query, instances, compilation, null, clr);
        List results = (List) eval.execute(true, true, true, true, true);
        assertEquals("Number of result instances was wrong", 1, results.size());
        Person p = (Person) results.get(0);
        assertEquals("Result instance has wrong first name", "Donald", p.getFirstName());
        assertEquals("Result instance has wrong last name", "Duck", p.getLastName());
        assertEquals("Person number of result instance is wrong", 102, p.getPersonNum());
        assertEquals("Age of result instance is wrong", 38, p.getAge());
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        fail("Exception thrown during query execution " + e.getMessage());
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
}
Also used : JDOQLCompiler(org.datanucleus.query.compiler.JDOQLCompiler) Query(org.datanucleus.store.query.Query) JDOQuery(org.datanucleus.api.jdo.JDOQuery) PersistenceManager(javax.jdo.PersistenceManager) HashMap(java.util.HashMap) JavaQueryInMemoryEvaluator(org.datanucleus.query.inmemory.JavaQueryInMemoryEvaluator) ArrayList(java.util.ArrayList) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) JDOQLInMemoryEvaluator(org.datanucleus.query.inmemory.JDOQLInMemoryEvaluator) JDOQuery(org.datanucleus.api.jdo.JDOQuery) Employee(org.jpox.samples.models.company.Employee) JavaQueryCompiler(org.datanucleus.query.compiler.JavaQueryCompiler) Transaction(javax.jdo.Transaction) ArrayList(java.util.ArrayList) List(java.util.List) QueryCompilation(org.datanucleus.query.compiler.QueryCompilation) Person(org.jpox.samples.models.company.Person)

Example 97 with Employee

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

the class JDOQLInMemoryTest method testAPISubquery.

/**
 * Test a subquery using the JDOQL Query API.
 */
public void testAPISubquery() {
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();
        // Persist 2 Employees
        Employee emp1 = new Employee(101, "F1", "S1", "f1.s1@company.com", 100f, "10001");
        Employee emp2 = new Employee(102, "F2", "S2", "f2.s2@company.com", 200f, "10002");
        pm.makePersistent(emp1);
        pm.makePersistent(emp2);
        pm.flush();
        // Find the Employees earning more than the average salary
        Query q = pm.newQuery(getQueryLanguage(), "SELECT FROM " + Employee.class.getName() + " WHERE salary > averageSalary");
        q.addExtension("datanucleus.query.evaluateInMemory", "true");
        q.declareVariables("double averageSalary");
        Query averageSalaryQuery = pm.newQuery(getQueryLanguage(), "SELECT avg(salary) FROM " + Employee.class.getName());
        q.addSubquery(averageSalaryQuery, "double averageSalary", null);
        List results = (List) q.execute();
        assertNotNull("No results from query!", results);
        assertEquals("Number of Employees with more than average salary was wrong", 1, results.size());
        tx.commit();
    } catch (JDOUserException e) {
        e.printStackTrace();
        fail(e.getMessage());
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
        clean(Employee.class);
    }
}
Also used : Employee(org.jpox.samples.models.company.Employee) Transaction(javax.jdo.Transaction) Query(javax.jdo.Query) PersistenceManager(javax.jdo.PersistenceManager) List(java.util.List) JDOUserException(javax.jdo.JDOUserException)

Example 98 with Employee

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

the class JDOQLInMemoryTest method testSingleStringSubquery.

/**
 * Test a subquery using the JDOQL Query as single-string.
 */
public void testSingleStringSubquery() {
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();
        // Persist 2 Employees
        Employee emp1 = new Employee(101, "F1", "S1", "f1.s1@company.com", 100f, "10001");
        Employee emp2 = new Employee(102, "F2", "S2", "f2.s2@company.com", 200f, "10002");
        pm.makePersistent(emp1);
        pm.makePersistent(emp2);
        pm.flush();
        // Find the Employees earning more than the average salary
        Query q = pm.newQuery(getQueryLanguage(), "SELECT FROM " + Employee.class.getName() + " WHERE salary > (SELECT avg(salary) FROM " + Employee.class.getName() + ")");
        q.addExtension("datanucleus.query.evaluateInMemory", "true");
        q.compile();
        List results = (List) q.execute();
        assertNotNull("No results from query!", results);
        assertEquals("Number of Employees with more than average salary was wrong", 1, results.size());
        tx.commit();
    } catch (JDOUserException e) {
        e.printStackTrace();
        fail(e.getMessage());
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
        clean(Employee.class);
    }
}
Also used : Employee(org.jpox.samples.models.company.Employee) Transaction(javax.jdo.Transaction) Query(javax.jdo.Query) PersistenceManager(javax.jdo.PersistenceManager) List(java.util.List) JDOUserException(javax.jdo.JDOUserException)

Example 99 with Employee

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

the class MultithreadedTest method processQueryAndDetach.

protected String processQueryAndDetach(boolean transaction) {
    List<Employee> results = null;
    PersistenceManager pm = pmf.getPersistenceManager();
    pm.setProperty(PropertyNames.PROPERTY_DETACH_ON_CLOSE, "true");
    pm.getFetchPlan().setGroup("all");
    pm.getFetchPlan().setMaxFetchDepth(-1);
    Transaction tx = pm.currentTransaction();
    try {
        if (transaction) {
            tx.begin();
        }
        Query<Employee> q = pm.newQuery(Employee.class);
        List<Employee> emps = q.executeList();
        results = new ArrayList<Employee>(emps);
        if (transaction) {
            tx.commit();
        }
    } catch (Throwable thr) {
        LOG.error("Exception query objects", thr);
        return "Exception in query : " + thr.getMessage();
    } finally {
        if (transaction && tx.isActive()) {
            tx.rollback();
        }
        // Detached the Employees and their loaded fields
        pm.close();
    }
    for (Employee e : results) {
        try {
            LOG.debug(">> Employee: " + e.getFirstName() + " " + e.getLastName() + " bestFriend=" + e.getBestFriend());
            if (e instanceof Manager) {
                Set subs = ((Manager) e).getSubordinates();
                if (subs == null) {
                    return "Manager object didnt have its subordinates detached!";
                } else if (subs.size() != 100) {
                    return "Manager had " + subs.size() + " subordinates instead of 100";
                }
            } else {
                Manager mgr = e.getManager();
                if (mgr == null) {
                    return "Employee=" + e + " didnt have its manager set!";
                } else {
                    Set<Employee> subs = mgr.getSubordinates();
                    if (subs == null) {
                        return "Employee=" + e + " didnt have its subordinates set!";
                    } else if (subs.size() != 100) {
                        return "Employee=" + e + " has Manager with " + subs.size() + " subordinates instead of 100";
                    }
                    for (Employee subE : subs) {
                        subE.toString();
                    }
                }
            }
        } catch (Exception exc) {
            LOG.error(">> Exception thrown on check of results", exc);
            return "Exception thrown : " + exc.getMessage();
        }
    }
    return null;
}
Also used : Employee(org.jpox.samples.models.company.Employee) Set(java.util.Set) Transaction(javax.jdo.Transaction) PersistenceManager(javax.jdo.PersistenceManager) Manager(org.jpox.samples.models.company.Manager) PersistenceManager(javax.jdo.PersistenceManager)

Example 100 with Employee

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

the class MultithreadedTest method testFind.

/**
 * Test that populates the datastore, and then starts many threads retrieving objects.
 */
public void testFind() {
    try {
        // Persist some data
        LOG.debug(">> Persisting data");
        PersistenceManager pm = pmf.getPersistenceManager();
        Transaction tx = pm.currentTransaction();
        Object mgrId = null;
        try {
            tx.begin();
            Manager mgr = new Manager(1, "The", "Boss", "the.boss@datanucleus.com", 200000, "100000");
            pm.makePersistent(mgr);
            for (int i = 0; i < 100; i++) {
                Employee emp = new Employee(i + 2, "FirstName" + i, "LastName" + i, "first.last." + i + "@datanucleus.com", 100000 + i, "12345" + i);
                emp.setManager(mgr);
                mgr.addSubordinate(emp);
                pm.makePersistent(emp);
            }
            tx.commit();
            mgrId = JDOHelper.getObjectId(mgr);
        } catch (Throwable thr) {
            LOG.error("Exception persisting objects", thr);
            fail("Exception persisting data : " + thr.getMessage());
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            pm.close();
        }
        LOG.debug(">> Persisted data");
        // Verify the persistence
        pm = pmf.getPersistenceManager();
        tx = pm.currentTransaction();
        try {
            tx.begin();
            Query<Employee> q = pm.newQuery(Employee.class);
            List<Employee> emps = q.executeList();
            for (Employee e : emps) {
                LOG.debug(">> emp=" + e + " e.mgr=" + e.getManager());
            }
            LOG.debug(">> Queried Employees");
            tx.commit();
        } catch (Throwable thr) {
            LOG.error("Exception checking objects", thr);
            fail("Exception checking data : " + thr.getMessage());
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            pm.close();
        }
        // Create the Threads
        int THREAD_SIZE = 500;
        final Object managerId = mgrId;
        final String[] threadErrors = new String[THREAD_SIZE];
        Thread[] threads = new Thread[THREAD_SIZE];
        for (int i = 0; i < THREAD_SIZE; i++) {
            final int threadNo = i;
            threads[i] = new Thread(new Runnable() {

                public void run() {
                    String errorMsg = processFind(managerId, true);
                    threadErrors[threadNo] = errorMsg;
                }
            });
        }
        // Run the Threads
        LOG.debug(">> Starting threads");
        for (int i = 0; i < THREAD_SIZE; i++) {
            threads[i].start();
        }
        for (int i = 0; i < THREAD_SIZE; i++) {
            try {
                threads[i].join();
            } catch (InterruptedException e) {
                fail(e.getMessage());
            }
        }
        LOG.debug(">> Completed threads");
        // Process any errors and fail the test if any threads failed present
        for (String error : threadErrors) {
            if (error != null) {
                fail(error);
            }
        }
    } finally {
        // Clean out data
        CompanyHelper.clearCompanyData(pmf);
    }
}
Also used : PersistenceManager(javax.jdo.PersistenceManager) Manager(org.jpox.samples.models.company.Manager) PersistenceManager(javax.jdo.PersistenceManager) Employee(org.jpox.samples.models.company.Employee) Transaction(javax.jdo.Transaction)

Aggregations

Employee (org.jpox.samples.models.company.Employee)129 PersistenceManager (javax.jdo.PersistenceManager)126 Transaction (javax.jdo.Transaction)119 Query (javax.jdo.Query)68 JDOUserException (javax.jdo.JDOUserException)62 Manager (org.jpox.samples.models.company.Manager)46 List (java.util.List)44 JDOPersistenceManager (org.datanucleus.api.jdo.JDOPersistenceManager)37 JDOObjectNotFoundException (javax.jdo.JDOObjectNotFoundException)24 Person (org.jpox.samples.models.company.Person)24 Collection (java.util.Collection)21 PersistenceManagerFactory (javax.jdo.PersistenceManagerFactory)18 Iterator (java.util.Iterator)17 Properties (java.util.Properties)17 JDODetachedFieldAccessException (javax.jdo.JDODetachedFieldAccessException)16 SQLException (java.sql.SQLException)12 StoreManager (org.datanucleus.store.StoreManager)12 Department (org.jpox.samples.models.company.Department)12 ArrayList (java.util.ArrayList)11 HashSet (java.util.HashSet)11