/** * INTERNAL: This method is used when computing the nested queries for batch read mappings. It * recurses computing the nested mapping queries. */ protected void computeNestedQueriesForBatchReadExpressions(Vector batchReadExpressions) { for (int index = 0; index < batchReadExpressions.size(); index++) { ObjectExpression objectExpression = (ObjectExpression) batchReadExpressions.get(index); // Expression may not have been initialized. ExpressionBuilder builder = objectExpression.getBuilder(); builder.setSession(getSession().getRootSession(null)); builder.setQueryClass(getReferenceClass()); // PERF: Cache join attribute names. ObjectExpression baseExpression = objectExpression; while (!baseExpression.getBaseExpression().isExpressionBuilder()) { baseExpression = (ObjectExpression) baseExpression.getBaseExpression(); } this.batchReadAttributes.add(baseExpression.getName()); // Ignore nested if (objectExpression.getBaseExpression().isExpressionBuilder()) { DatabaseMapping mapping = objectExpression.getMapping(); if ((mapping != null) && mapping.isForeignReferenceMapping()) { // A nested query must be built to pass to the descriptor that looks like the real query // execution would. ReadQuery nestedQuery = ((ForeignReferenceMapping) mapping).prepareNestedBatchQuery(this); // Register the nested query to be used by the mapping for all the objects. getBatchReadMappingQueries().put(mapping, nestedQuery); } } } }
public static BinaryOperatorWithParameterTest getNumericParameterDivideTest() { BinaryOperatorWithParameterTest theTest = new BinaryOperatorWithParameterTest(); theTest.setName("Divide with parameter test"); String parameterName = "amountToDivide"; theTest.setExpressionParameters(new Vector()); theTest.getExpressionParameters().add(parameterName); ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = ExpressionMath.divide(builder.get("salary"), (builder.getParameter(parameterName))) .lessThanEqual(20000); theTest.setOriginalObjectExpression(whereClause); String ejbqlString = "SELECT OBJECT(emp) FROM Employee emp WHERE emp.salary / ?1 <= 20000"; theTest.setEjbqlString(ejbqlString); Vector myArgumentNames = new Vector(); myArgumentNames.add("1"); theTest.setArgumentNames(myArgumentNames); theTest.setArguments(new Vector()); theTest.getArguments().addElement(new Integer(2)); return theTest; }
public void setup() { Employee emp = (Employee) getSomeEmployees().firstElement(); String partOne; String partTwo; String ejbqlString; partOne = emp.getFirstName(); ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = builder.get("firstName").concat("Smith").like(partOne + "Smith"); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); raq.setSelectionCriteria(whereClause); Vector employees = (Vector) getSession().executeQuery(raq); ejbqlString = "SELECT OBJECT(emp) FROM Employee emp WHERE "; ejbqlString = ejbqlString + "CONCAT(emp.firstName,\"Smith\") LIKE "; ejbqlString = ejbqlString + "\"" + partOne + "Smith\""; setEjbqlString(ejbqlString); setOriginalOject(employees); super.setup(); }
public void setup() { setReferenceClass(Employee.class); // add a mapping for addressId so we can use it in from "emp" // DirectToFieldMapping addressIdMapping = new DirectToFieldMapping(); // addressIdMapping.setAttributeName("addressId"); // addressIdMapping.setFieldName("EMPLOYEE.ADDR_ID"); // addressIdMapping.setGetMethodName("getAddressId"); // addressIdMapping.setSetMethodName("setAddressId"); // addressIdMapping.setIsReadOnly(true); // getSession().getDescriptor(Employee.class).addMapping(addressIdMapping); // addressIdMapping.initialize(getSession()); ExpressionBuilder builder = new ExpressionBuilder(Employee.class); ExpressionBuilder addressBuilder = new ExpressionBuilder(Address.class); Expression whereClause = builder.get("addressId").equal(addressBuilder.get("id")); Vector employees = getSession().readAllObjects(Employee.class, whereClause); setOriginalOject(employees); getSession().getIdentityMapAccessor().initializeAllIdentityMaps(); String ejbqlString; ejbqlString = "SELECT OBJECT(emp) FROM Employee emp, Address address " + "WHERE emp.addressId = address.id"; setEjbqlString(ejbqlString); super.setup(); }
public void setup() { Employee emp1; Employee emp2; Employee emp3; emp1 = (Employee) getSomeEmployees().firstElement(); emp2 = (Employee) getSomeEmployees().elementAt(1); emp3 = (Employee) getSomeEmployees().elementAt(2); ExpressionBuilder builder = new ExpressionBuilder(); Vector idVector = new Vector(); idVector.add(emp1.getId()); idVector.add(emp2.getId()); idVector.add(emp3.getId()); Expression whereClause = builder.get("id").notIn(idVector); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); raq.setSelectionCriteria(whereClause); setOriginalOject(getSession().executeQuery(raq)); getSession().getIdentityMapAccessor().initializeAllIdentityMaps(); String ejbqlString = "SELECT OBJECT(emp) FROM Employee emp WHERE emp.id NOT IN ("; ejbqlString = ejbqlString + emp1.getId().toString() + ", "; ejbqlString = ejbqlString + emp2.getId().toString() + ", "; ejbqlString = ejbqlString + emp3.getId().toString(); ejbqlString = ejbqlString + ")"; setEjbqlString(ejbqlString); super.setup(); }
public void setup() { Vector employees = getSomeEmployees(); // Bug 223005: Verify that we have at least 1 employee with the required field length otherwise // an EclipseLinkException will be thrown Employee emp = getEmployeeWithRequiredNameLength(employees, MIN_FIRSTNAME_LENGTH, getName()); String partialFirstName = "%" + emp.getFirstName().substring(0, 3) + "%"; ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); Vector parameters = new Vector(); parameters.add(partialFirstName); ExpressionBuilder eb = new ExpressionBuilder(); Expression whereClause = eb.get("firstName").like(partialFirstName); raq.setSelectionCriteria(whereClause); employees = (Vector) getSession().executeQuery(raq); String ejbqlString = "SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName LIKE ?1"; setEjbqlString(ejbqlString); setOriginalOject(employees); setArguments(parameters); Vector myArgumentNames = new Vector(); myArgumentNames.add("1"); setArgumentNames(myArgumentNames); super.setup(); }
public static BinaryOperatorWithParameterTest getNumericParameterDivideTestWithBracketsAfterComparison() { BinaryOperatorWithParameterTest theTest = new BinaryOperatorWithParameterTest(); theTest.setName("Divide with parameter test with brackets after comparison"); String parameterName = "amountToDivide"; theTest.setExpressionParameters(new Vector()); theTest.getExpressionParameters().add(parameterName); ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = ExpressionBuilder.fromConstant(new Integer(20000), builder) .greaterThan( ExpressionMath.divide( builder.get("salary"), (builder.getParameter(parameterName)))); theTest.setOriginalObjectExpression(whereClause); String ejbqlString = "SELECT OBJECT(emp) FROM Employee emp WHERE 20000 > (emp.salary / ?1)"; theTest.setEjbqlString(ejbqlString); Vector myArgumentNames = new Vector(); myArgumentNames.add("1"); theTest.setArgumentNames(myArgumentNames); theTest.setArguments(new Vector()); theTest.getArguments().addElement(new Integer(2)); return theTest; }
public static BinaryOperatorWithParameterTest getNumericParameterMultiplyTestWithBracketsBeforeComparison() { BinaryOperatorWithParameterTest theTest = new BinaryOperatorWithParameterTest(); theTest.setName("Multiply with parameter test with brackets before comparison"); String parameterName = "amountToMultiply"; theTest.setExpressionParameters(new Vector()); theTest.getExpressionParameters().add(parameterName); ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = ExpressionMath.multiply(builder.get("salary"), (builder.getParameter(parameterName))) .lessThanEqual(100000); theTest.setOriginalObjectExpression(whereClause); String ejbqlString = "SELECT OBJECT(emp) FROM Employee emp WHERE (emp.salary * ?1) <= 100000"; theTest.setEjbqlString(ejbqlString); Vector myArgumentNames = new Vector(); myArgumentNames.add("1"); theTest.setArgumentNames(myArgumentNames); theTest.setArguments(new Vector()); theTest.getArguments().addElement(new Integer(2)); return theTest; }
public ReadQuery getQueryForTest() { ReportQuery testQuery = new ReportQuery(); testQuery.setReferenceClass(Employee.class); ExpressionBuilder employees = new ExpressionBuilder(); Expression exp = employees.get("firstName").like("B%"); testQuery.setSelectionCriteria(exp); testQuery.cacheQueryResults(); testQuery.addAttribute("firstName"); return testQuery; }
protected void verify() { // Check to see that aCountry was not deleted from the database. ExpressionBuilder xBuilder = new ExpressionBuilder(); Expression exp = xBuilder.get("name").equal(aCountry.name); Country dbCountry = (Country) getSession().readObject(Country.class, exp); if (dbCountry != null) { throw new TestErrorException( "The Country object was illegally updated! It should not have been!"); } }
public void test() { ExpressionBuilder eb = new ExpressionBuilder(); ReportQuery rq = new ReportQuery(Employee.class, eb); rq.addAttribute("firstName"); rq.addAttribute("lastName"); Expression exp = eb.getFunction("dbms_random.value"); exp.setSelectIfOrderedBy(false); rq.addOrdering(exp.ascending()); rq.setSelectionCriteria(eb.anyOf("projects").get("teamLeader").isNull()); results = (Vector) getSession().executeQuery(rq); }
/** Read employee and clear the cache, test database read. */ public void test() throws Exception { ReadObjectQuery query = new ReadObjectQuery(Employee.class); ExpressionBuilder employee = new ExpressionBuilder(); query.setSelectionCriteria( employee .get("firstName") .equal("Brendan") .and(employee.get("salary").equal(100000)) .and(employee.get("address").get("city").like("%pean%")) .and(employee.anyOf("phoneNumbers").get("type").equal("Home"))); query.checkCacheOnly(); Employee result = (Employee) getSession().executeQuery(query); }
protected void applyBadExp(ScopedName op, Object[] operands) { ExpressionPtr exp = new ExpressionPtr(op, operands); try { eb.apply(exp); assertTrue(false); } catch (ApologyException ae) { d.msg(Debug.COMPILE, EX_AP + ae.getMessage()); } }
public void setup() { setReferenceClass(Employee.class); ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = builder.anyOf("managedEmployees").get("address").get("city").equal("Ottawa"); Vector employees = getSession().readAllObjects(Employee.class, whereClause); setOriginalOject(employees); getSession().getIdentityMapAccessor().initializeAllIdentityMaps(); String ejbqlString; ejbqlString = "SELECT OBJECT(emp) FROM Employee emp, IN(emp.managedEmployees) managedEmployees " + "WHERE managedEmployees.address.city = 'Ottawa'"; setEjbqlString(ejbqlString); super.setup(); }
protected void test() { for (int i = 0; i <= 1; i++) { getSession().getPlatform().setShouldBindAllParameters(i != 0); for (int j = 0; j <= 2; j++) { query = new ReadAllQuery(Employee.class); ExpressionBuilder builder = new ExpressionBuilder(); Vector vExp = new Vector(2); vExp.add(builder.getParameter("p1")); query.addArgument("p1"); vExp.add(builder.getParameter("p2")); query.addArgument("p2"); Expression exp = builder.get("id").in(vExp); query.setSelectionCriteria(exp); switch (j) { case 0: // nothing to do - just test the default: // query.bindAllParameters == Undefined break; case 1: // query.bindAllParameters == False query.setShouldBindAllParameters(false); break; case 2: // query.bindAllParameters == True query.setShouldBindAllParameters(true); break; } // clear the writer's buffer ((StringWriter) getSession().getLog()).getBuffer().setLength(0); try { getSession().executeQuery(query, v); } catch (DatabaseException e) { throw new TestProblemException("executeQuery threw DatabaseException"); } if (shouldBind() != wasBound()) { return; } } } }
public static BinaryOperatorWithParameterTest getNumericParameterLessThanEqualTest() { BinaryOperatorWithParameterTest theTest = new BinaryOperatorWithParameterTest(); theTest.setName("Less than equal to with parameter test"); String parameterName = "id"; theTest.setExpressionParameters(new Vector()); theTest.getExpressionParameters().add(parameterName); ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = builder.get("id").lessThanEqual(builder.getParameter(parameterName)); theTest.setOriginalObjectExpression(whereClause); String ejbqlString = "SELECT OBJECT(emp) FROM Employee emp WHERE "; ejbqlString = ejbqlString + "emp.id <= ?1 "; theTest.setEjbqlString(ejbqlString); Vector myArgumentNames = new Vector(); myArgumentNames.add("1"); theTest.setArgumentNames(myArgumentNames); return theTest; }
/** * INTERNAL: Selection criteria is created with source foreign keys and target keys. This criteria * is then used to read target records from the table. */ public void initializeSelectionCriteria(AbstractSession session) { Expression selectionCriteria = null; Expression expression; ExpressionBuilder expBuilder = new ExpressionBuilder(); Iterator sourceKeysEnum = getSourceToTargetQueryKeyNames().keySet().iterator(); while (sourceKeysEnum.hasNext()) { DatabaseField sourceKey = (DatabaseField) sourceKeysEnum.next(); String target = (String) this.getSourceToTargetQueryKeyNames().get(sourceKey); expression = expBuilder.getParameter(sourceKey).equal(expBuilder.get(target)); if (selectionCriteria == null) { selectionCriteria = expression; } else { selectionCriteria = expression.and(selectionCriteria); } } setSelectionCriteria(selectionCriteria); }
public void setup() { Employee emp = (Employee) getSomeEmployees().firstElement(); PhoneNumber phone = (PhoneNumber) emp.getPhoneNumbers().firstElement(); String areaCode = phone.getAreaCode(); String firstName = emp.getFirstName(); setReferenceClass(Employee.class); ExpressionBuilder employeeBuilder = new ExpressionBuilder(); Expression phones = employeeBuilder.anyOf("phoneNumbers"); Expression whereClause = phones .get("owner") .get("firstName") .equal(firstName) .and(phones.get("areaCode").equal(areaCode)); ReportQuery rq = new ReportQuery(); rq.setSelectionCriteria(whereClause); rq.addAttribute("number", phones.get("number")); rq.setReferenceClass(Employee.class); setOriginalOject(getAttributeFromAll("number", (Vector) getSession().executeQuery(rq))); getSession().getIdentityMapAccessor().initializeAllIdentityMaps(); String ejbqlString; ejbqlString = "SELECT phone.number FROM Employee employee, IN(employee.phoneNumbers) phone " + "WHERE phone.owner.firstName = \"" + firstName + "\" AND phone.areaCode = \"" + areaCode + "\""; useReportQuery(); setEjbqlString(ejbqlString); super.setup(); }
public static BinaryOperatorWithParameterTest getNumericTwoParameterMultipleOperators() { BinaryOperatorWithParameterTest theTest = new BinaryOperatorWithParameterTest(); theTest.setName("Multiple operators with two parameters"); String parameterNameForDivide = "amountToDivide"; String parameterNameForMultiply = "amountToMultiply"; theTest.setExpressionParameters(new Vector()); theTest.getExpressionParameters().add(parameterNameForDivide); theTest.getExpressionParameters().add(parameterNameForMultiply); ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = ExpressionMath.subtract( ExpressionMath.add(builder.get("salary"), 10000), ExpressionMath.multiply( ExpressionMath.divide( ExpressionBuilder.fromConstant(new Integer(10000), builder), builder.getParameter(parameterNameForDivide)), builder.getParameter(parameterNameForMultiply))) .greaterThanEqual(50000); theTest.setOriginalObjectExpression(whereClause); String ejbqlString = "SELECT OBJECT(emp) FROM Employee emp WHERE emp.salary + 10000 - 10000 / ?1 * ?2 >= 50000"; theTest.setEjbqlString(ejbqlString); Vector myArgumentNames = new Vector(); myArgumentNames.add("1"); myArgumentNames.add("2"); theTest.setArgumentNames(myArgumentNames); theTest.setArguments(new Vector()); theTest.getArguments().addElement(new Integer(2)); theTest.getArguments().addElement(new Integer(3)); return theTest; }
public void setup() { // Get the baseline employees for the verify Employee emp = (Employee) getSomeEmployees().firstElement(); String parameterName = "firstName"; ExpressionBuilder builder = new ExpressionBuilder(); Expression whereClause = builder.get("firstName").equal(builder.getParameter(parameterName)); ReadAllQuery raq = new ReadAllQuery(); raq.setReferenceClass(Employee.class); raq.setSelectionCriteria(whereClause); raq.addArgument(parameterName); Vector parameters = new Vector(); parameters.add(emp.getFirstName()); Vector employees = (Vector) getSession().executeQuery(raq, parameters); emp = (Employee) employees.firstElement(); // Set up the EJBQL using the retrieved employees String ejbqlString = "SELECT OBJECT(emp) FROM Employee emp WHERE "; ejbqlString = ejbqlString + "?1 = emp.firstName "; setEjbqlString(ejbqlString); setOriginalOject(employees); setArguments(parameters); Vector myArgumentNames = new Vector(); myArgumentNames.add("1"); setArgumentNames(myArgumentNames); // Finish the setup super.setup(); }
/** Read all employees with salary > 0. */ public void test() throws Exception { ReadAllQuery query = new ReadAllQuery(Employee.class); ExpressionBuilder builder = new ExpressionBuilder(); query.setSelectionCriteria(builder.get("salary").greaterThan(0)); List results = (List) getSession().executeQuery(query); }
protected ExpressionNode applyExp(ScopedName op, Object[] operands) { ExpressionPtr exp = new ExpressionPtr(op, operands); eb.apply(exp); return exp.get(); }
/** INTERNAL: Conform the result if specified. */ protected Object conformResult( Object result, UnitOfWorkImpl unitOfWork, AbstractRecord arguments, boolean buildDirectlyFromRows) { if (getSelectionCriteria() != null) { ExpressionBuilder builder = getSelectionCriteria().getBuilder(); builder.setSession(unitOfWork.getRootSession(null)); builder.setQueryClass(getReferenceClass()); } // If the query is redirected then the collection returned might no longer // correspond to the original container policy. CR#2342-S.M. ContainerPolicy cp; if (getRedirector() != null) { cp = ContainerPolicy.buildPolicyFor(result.getClass()); } else { cp = getContainerPolicy(); } // This code is now a great deal different... For one, registration is done // as part of conforming. Also, this should only be called if one actually // is conforming. // First scan the UnitOfWork for conforming instances. // This will walk through the entire cache of registered objects. // Let p be objects from result not in the cache. // Let c be objects from cache. // Presently p intersect c = empty set, but later p subset c. // By checking cache now doesConform will be called p fewer times. Map indexedInterimResult = unitOfWork.scanForConformingInstances( getSelectionCriteria(), getReferenceClass(), arguments, this); Cursor cursor = null; // In the case of cursors just conform/register the initially read collection. if (cp.isCursorPolicy()) { cursor = (Cursor) result; cp = ContainerPolicy.buildPolicyFor(ClassConstants.Vector_class); // In nested UnitOfWork session might have been session of the parent. cursor.setSession(unitOfWork); result = cursor.getObjectCollection(); // for later incremental conforming... cursor.setInitiallyConformingIndex(indexedInterimResult); cursor.setSelectionCriteriaClone(getSelectionCriteria()); cursor.setTranslationRow(arguments); } // Now conform the result from the database. // Remove any deleted or changed objects that no longer conform. // Deletes will only work for simple queries, queries with or's or anyof's may not return // correct results when untriggered indirection is in the model. Vector fromDatabase = null; // When building directly from rows, one of the performance benefits // is that we no longer have to wrap and then unwrap the originals. // result is just a vector, not a container of wrapped originals. if (buildDirectlyFromRows) { Vector rows = (Vector) result; fromDatabase = new Vector(rows.size()); for (int i = 0; i < rows.size(); i++) { Object object = rows.elementAt(i); // null is placed in the row collection for 1-m joining to filter duplicate rows. if (object != null) { Object clone = conformIndividualResult( object, unitOfWork, arguments, getSelectionCriteria(), indexedInterimResult, buildDirectlyFromRows); if (clone != null) { fromDatabase.addElement(clone); } } } } else { fromDatabase = new Vector(cp.sizeFor(result)); AbstractSession sessionToUse = unitOfWork.getParent(); for (Object iter = cp.iteratorFor(result); cp.hasNext(iter); ) { Object object = cp.next(iter, sessionToUse); Object clone = conformIndividualResult( object, unitOfWork, arguments, getSelectionCriteria(), indexedInterimResult, buildDirectlyFromRows); if (clone != null) { fromDatabase.addElement(clone); } } } // Now add the unwrapped conforming instances into an appropriate container. // Wrapping is done automatically. // Make sure a vector of exactly the right size is returned. Object conformedResult = cp.containerInstance(indexedInterimResult.size() + fromDatabase.size()); Object eachClone; for (Iterator enumtr = indexedInterimResult.values().iterator(); enumtr.hasNext(); ) { eachClone = enumtr.next(); cp.addInto(eachClone, conformedResult, unitOfWork); } for (Enumeration enumtr = fromDatabase.elements(); enumtr.hasMoreElements(); ) { eachClone = enumtr.nextElement(); cp.addInto(eachClone, conformedResult, unitOfWork); } if (cursor != null) { cursor.setObjectCollection((Vector) conformedResult); // For nested UOW must copy all in object collection to // initiallyConformingIndex, as some of these could have been from // the parent UnitOfWork. if (unitOfWork.isNestedUnitOfWork()) { for (Enumeration enumtr = cursor.getObjectCollection().elements(); enumtr.hasMoreElements(); ) { Object clone = enumtr.nextElement(); indexedInterimResult.put(clone, clone); } } return cursor; } else { return conformedResult; } }
public void test() { ReadAllQuery query = new ReadAllQuery(); ScrollableCursor cursor = null; try { query.setReferenceClass(Employee.class); if (TYPE_SCROLL_INSENSITIVE_isSupported && CONCUR_UPDATABLE_isSupported) { query.useScrollableCursor(2); } else { ScrollableCursorPolicy policy = new ScrollableCursorPolicy(); if (!TYPE_SCROLL_INSENSITIVE_isSupported) { policy.setResultSetType(ScrollableCursorPolicy.TYPE_SCROLL_SENSITIVE); } if (!CONCUR_UPDATABLE_isSupported) { policy.setResultSetConcurrency(ScrollableCursorPolicy.CONCUR_READ_ONLY); } policy.setPageSize(2); query.useScrollableCursor(policy); } // if (configuration != null) { ExpressionBuilder builder = new ExpressionBuilder(); Expression exp = builder.get("salary").greaterThan(50000); query.setSelectionCriteria(exp); query.conformResultsInUnitOfWork(); } cursor = (ScrollableCursor) getSession().executeQuery(query); try { // test to see if we can iterate through a list and then iterate // in reverse through the same list. int totalItems = 0; while (cursor.hasNext()) { readWithNext.addElement(cursor.next()); totalItems++; } while (cursor.hasPrevious()) { readWithPrevious.addElement(cursor.previous()); totalItems--; } cursorSuccess = (totalItems == 0); int size = readWithPrevious.size(); for (int i = 0; i < readWithNext.size(); i++) { cursorSuccess = (cursorSuccess && (readWithNext.elementAt(i) == readWithPrevious.elementAt((size - 1) - i))); } } catch (org.eclipse.persistence.exceptions.QueryException ex) { caughtException = ex; } } finally { if (cursor != null) { cursor.close(); } } }