Archive for October, 2006

142 Queries with JDOQL Now that it has

Monday, October 30th, 2006

Unconstrained query variables 143 Extent partnerExt = pm.getExtent(BusinessPartner.class, true); String filter = “customer.orders.contains(o) && o.dispatched == false”; Query q = pm.newQuery(partnerExt, filter); q.declareVariables(”Order o”); Collection c = (Collection) q.execute(); The filter criteria could also be legally written using the logical complement operator (!) as follows: customer.orders.contains(o) && !o.dispatched Conceptually, o is set to each contained Order in turn and !o.dispatched is then evaluated. In practice, queries are usually translated into the native query language of the underlying data store in order to take best advantage of the available indexing and query tuning strategies. Thus explicit serial evaluation of individual order entities is unlikely. 8.7 Unconstrained query variables The primary purpose of JDOQL variables is as identifiers for use in contains() clauses, facilitating the iteration through persistent fields of Collection type. However, the JDO specification does allow for the definition of query variables that are subsequently referenced in the filter expression, but not subject to a contains() clause. Such identifiers, known as unconstrained query variables, conceptually iterate across the entire extent (including subclasses) of their persistence-capable type. The specification is particularly vague about the portability of query filters using unconstrained variables, and I will not discuss the concept further here. It has, however, been the subject of several threads of discussion at JDOcentral, and will certainly be clarified in the next version of the specification document. 8.8 Dynamic Query Window You will have noticed that all query elements are passed as strings. This has one disadvantage; query syntax is checked only at query compilation or execution time. In most cases, query errors will be detected only during the running of the application. However, it does facilitate the writing of applications that execute ad hoc queries, the details of which are not known at compile time. An example is the Dynamic Query Window, shown in Figure 8.2. This is a relatively simple Swing application. It uses the JDOBootstrap class to initialize JDO, so all of the configuration parameters can go into the jdo.properties file. It then allows the user to enter the various query element strings. Upon

Hint: If you are looking for very good and affordable webspace to host and run your tomcat hosting application check Virtualwebstudio tomcat web hosting provider

142 Queries with JDOQL Now that it has

Monday, October 30th, 2006

142 Queries with JDOQL Now that it has multiple parameters, the query execution can be rewritten to show the meaningful use of named parameters. This is particularly useful when the code executing the query is separate from the code constructing the query and requesting parameter values. Here we use a HashMap to hold the parameters: Extent partnerExt = pm.getExtent(BusinessPartner.class, true); String filter = “name == searchName && address == searchAddress”; Query q = pm.newQuery(partnerExt, filter); q.declareParameters(”String searchName, String searchAddress”); q.setOrdering(”name ascending, partnerId descending”); Map m = new HashMap(); m.add(”searchAddress”, “Milton Keynes”); m.add(”searchName”, “Ogilvie Partners”); Collection c = (Collection) q.executeWithMap(m); Notice that the order in which parameters are added to the map is insignificant. I have deliberately shown the reverse order being used to reinforce this concept. 8.6.2 Singleton field navigation The next item to illustrate is the de-referencing of persistent fields that refer to other persistent objects. Let s write a query that retrieves all business partners with a credit limit greater than a parameter value. Notice that the credit limit is stored on the Customer instance. Extent partnerExt = pm.getExtent(BusinessPartner.class, true); String filter = “customer.creditLimit > searchCredit”; Query q = pm.newQuery(partnerExt, filter); q.declareParameters(”double searchCredit”); Double credit = new Double(1000); Collection c = (Collection) q.execute(credit); The above query de-references a singleton field. The customer field either references a single Customer object, or it is null. If the field is null, then attempts to de-reference it will cause that filter subexpression to evaluate to false. Since there is only one such subexpression, the filter will evaluate to false. Thus, BusinessPartners that are not Customers will be excluded from the query results. 8.6.3 Collection field navigation Our final query example illustrates navigation through collections. Here we identify the list of BusinessPartners that have at least one Order that has not yet been dispatched. This requires the definition of a variable to reference each Order that is examined.

Hint: If you are looking for very good and affordable webspace to host and run your tomcat hosting application check Virtualwebstudio tomcat web hosting provider

140 Queries with JDOQL 8.5.3.2. Equality The equality

Sunday, October 29th, 2006

Further examples 141 8.6 Further examples Now that you know a bit more about JDOQL s capabilities and syntax, let s look at some slightly more complicated examples. 8.6.1 Parameterization Our previous example employed the simple JDOQL filter name == “Ogilvie Partners” Now we ll add parameterization. The test will no longer be against the string literal Ogilvie Partners, but against an incoming string parameter. Extent partnerExt = pm.getExtent(BusinessPartner.class, true); String filter = “name == searchName”; Query q = pm.newQuery(partnerExt, filter); q.declareParameters(”String searchName”); q.setOrdering(”name ascending, partnerId descending”); Collection c = (Collection) q.execute(”Ogilvie Partners”); The filter has been changed, so that name is compared with searchName. In turn, searchName is declared as a parameter to the query. Finally a String is passed to the query execution method. It is permissible for the query parameter to have the same name as a persistent field. In such cases, the keyword “this” is used to differentiate between the two, as per the example below. Extent partnerExt = pm.getExtent(BusinessPartner.class, true); String filter = “this.name == name”; Query q = pm.newQuery(partnerExt, filter); q.declareParameters(”String name”); q.setOrdering(”name ascending, partnerId descending”); Collection c = (Collection) q.execute(”Ogilvie Partners”); There is only one parameter in this case. If there had been multiple parameters, the parameter declaration would be comma-delimited. Parameters would be bound to values at runtime according to the sequences with which parameter declarations and values were given. In this regard they are positional parameters. Here is an example with multiple parameters: Extent partnerExt = pm.getExtent(BusinessPartner.class, true); String filter = “name == searchName && address == searchAddress”; Query q = pm.newQuery(partnerExt, filter); q.declareParameters(”String searchName, String searchAddress”); q.setOrdering(”name ascending, partierId descending”); Collection c; c = (Collection) q.execute(”Ogilvie Partners”, “Milton Keynes”);
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra servlet hosting services

140 Queries with JDOQL 8.5.3.2. Equality The equality

Sunday, October 29th, 2006

140 Queries with JDOQL 8.5.3.2. Equality The equality operator == can be used between primitives and instances of the corresponding wrapper types. Thus, if an identifier (field or parameter) called intPrimitive is of type int, and identifier intWrapper is of type Integer, the following comparison is legal in JDOQL (but would be illegal in Java): intPrimitive == intWrapper This is also extended to equality of String and Date objects. Note that equality comparisons (== and !=) between floating point values are inherently inexact and should be used with caution. The results of such com parisons may vary across different JDO implementations. 8.5.3.3 Ordering As with equality, the ordering operators (>, <, >=, <=) can be used between primitives and instances of the corresponding wrapper types. With the identifiers defined above, the following comparison is legal in JDOQL (but would be illegal in Java): intPrimitive > intWrapper This is again extended to ordering of String and Date objects. 8.5.3.4 Assignment A query filter may not do anything that might change the value of a persistent field. Specifically the assignment operators (=, +=, /=, etc.) and the pre/post increment/decrement operators (++ and –) are illegal. Implementations may optionally permit the invocation of methods, on persistence-capable or system classes, as long as these methods are themselves non-mutating. 8.5.3.5 Navigation JDOQL explicitly supports navigation from one instance to another, by use of the de-reference operator (the period). Queries can navigate from one instance to another through a singleton (non-collection) reference. Queries can also navigate through multivalued Collection fields by using the Collection.contains() method. Attempted navigation through a null reference causes that subexpression to evaluate to false. Other subexpression evaluations, combined with the logical operators, may still cause the instance to be included in the query s result.
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra servlet hosting services

138 Queries with JDOQL Table 8.2 Comparative operators

Sunday, October 29th, 2006

Query filter expressions 139 8.5.3 Differences between JDOQL and Java operators There are a number of differences between the usage of these operators in JDOQL and their usage in Java. Many of the differences serve to streamline the query language, making it more intuitive. 8.5.3.1 Method invocation JDOQL is a language for querying persistent instances from a data store. It is not, as some people have believed, a fully fledged object query language. This is borne out by the restriction that method invocations are largely illegal in JDOQL filters. This restriction means that a JDO implementation is not required to instantiate an instance in order to determine whether it matches the given query filter criteria. Query performance is therefore greatly improved. Four legal method invocations are defined. The filter may apply the following invocations to persistent fields of Collection type: isEmpty() Returns true if the persistent field is null or references a Collection that con tains no elements. contains(Object o) Returns true if the persistent field references a Collection that contains the identified persistence-capable object. The object o must be a persistence-capable instance. Equality between persistent instances always uses JDO identity, and is irrespective of any equals() method that may be defined. Conceptually the contains(Object o) method is used to iterate the local variable o over the elements of a Collection. It is used as the left-hand side of a boolean expression, and evaluates to true if any one element of the Collection satisfies that expression. The filter may apply the following invocations to persistent fields of String type: startsWith(String s) Returns true if the persistent field to which the method is applied starts with the designated string. endsWith(String s) Returns true if the persistent field to which the method is applied ends with the designated string. Vendors may add support for other method invocations as long as these are non- mutating. A non-mutating method is one that does not alter the state of any objects. Such additions will be well documented, but should not be considered portable across implementations. A few vendors are already supporting the String methods indexOf()and toLower(), with support for further invocations to follow.
Note: If you are looking for inexpensive but high quality provider to host and run your jsp application check Astra jsp hosting services

138 Queries with JDOQL Table 8.2 Comparative operators

Sunday, October 29th, 2006

138 Queries with JDOQL Table 8.2 Comparative operators Operator Description == Equal != Not equal > Greater than < Less than >= Greater than or equal <= Less than or equal + Numeric addition and string concatenation * Multiplication / Division JDOQL supports the casting and de-referencing of fields that are reference types. Both are performed using the familiar Java operators, shown in Table 8.3. Table 8.3 Reference operators Operator Description (Class) Object casting . De-reference a reference type field (as in field1.field2) Finally JDOQL supports the following unary operators, which apply to the expression immediately to their right (Table 8.4). Table 8.4 Unary operators Operator Description ~ Integral bit-wise complement Numeric sign inversion 8.5.2 Supported keywords The keyword this is a reserved word in JDOQL. It is used in filter expressions to refer to the instance of the candidate collection for which the filter expression is currently being evaluated. It can also be used to differentiate between persistent fields of the candidate class and identically named query parameters. An example of such usage is given under section 8.6.1.
Note: If you are looking for inexpensive but high quality provider to host and run your jsp application check Astra jsp hosting services

136 Queries with JDOQL collection is the entire

Sunday, October 29th, 2006

Query filter expressions 137 Query filters are expressions that evaluate to a boolean value. They are structured as zero, one, or more boolean expressions separated by logical NOT (complement), AND, and OR operators, in that order of evaluation. Parentheses may be used to alter the default order of evaluation. For readers well versed in formal grammars, the grammar for JDOQL is reproduced in Appendix E, in Backus-Naur Form (BNF). 8.5.1 Supported operators Five logical operators are defined. These are listed and described in Table 8.1. Table 8.1 Logical operators Operator Description ! NOT (complement) Negates the logical expression to its right & Unconditional AND Causes the expressions to its left and right to be evaluated, and returns the result of a logical AND operation of the resulting boolean values && Conditional AND Causes the evaluation of the expression to its left. If this is false, the result of the AND expression is false; otherwise the expression on its right is evaluated, the result of the AND expression being the result of the right-hand boolean expression | Unconditional OR Causes the expressions to its left and right to be evaluated, and returns the result of a logical OR operation of the resulting boolean values | | Conditional OR Causes the evaluation of the expression to its left. If this is true, the result of the OR expression is true; otherwise the expression on its right is evaluated, the result of the OR expression being the result of the right-hand boolean expression JDOQL filters must be non-mutating, which means that their evaluation will have no side effects. Thus there is no justification for using the unconditional logical operators (&, |), and the conditional ones (&&, ||) should be used as a matter of course. Indeed, many JDO implementations replace & with && and | with || during query execution. JDOQL supports a complete set of comparative operators. These return boolean values based on evaluating the results of the left and right-hand expressions. They are shown in Table 8.2.

Hint: If you are looking for high quality and reliable webspace provider to host and run your jsp hosting application check Virtualwebstudio jsp web hosting provider

136 Queries with JDOQL collection is the entire

Sunday, October 29th, 2006

136 Queries with JDOQL collection is the entire extent of BusinessPartner (including subclasses). It is important to note that the objects being returned each time next() is called on the Iterator are in fact instances of the concrete subclasses of BusinessPartner: Company, Charity, and Individual. 8.4.2 Query with ordering The next step is to add a simple ordering declaration. The example below orders the query results according to name, and then according to partnerId descending. Thus if multiple partners had the same name they would appear in the descending sequence of their partnerIds. Extent partnerExt = pm.getExtent(BusinessPartner.class, true); Query q = pm.newQuery(partnerExt); q.setOrdering(”name ascending, partnerId descending”); Collection c = (Collection) q.execute(); The ordering declaration comprises any number of persistent field names, each paired with the keyword ascending or descending as appropriate. These pairs are separated with commas. 8.4.3 Query with filter For our next example, let s apply a simple filter to the query. We will discuss the full suite of available filter operators shortly. For now we will use the == operator to select only those business partners with a specific name. Extent partnerExt = pm.getExtent(BusinessPartner.class, true); String filter = “name == “Ogilvie Partners”"; Query q = pm.newQuery(partnerExt, filter); q.setOrdering(”name ascending, partnerId descending”); Collection c = (Collection) q.execute(); We are now using a different newQuery() method that returns a query with the filter declaration assigned. The filter declaration is a String containing the boolean expression. Although this expression is based on Java syntax there are significant differences, such as the use of the == operator for testing string equivalence above. In the next section we examine the capabilities and syntax of filter expressions in detail. 8.5 Query filter expressions The filter expression for a query is optional. If no filter is set, the filter will be deemed to evaluate to true in all cases, and the query result will be the whole candidate collection.

Hint: If you are looking for high quality and reliable webspace provider to host and run your jsp hosting application check Virtualwebstudio jsp web hosting provider

134 Queries with JDOQL Query compilation is generally

Saturday, October 28th, 2006

Query examples 135 8.4.1 Query without filter Our first example is a query that lists all instances of the BusinessPartner class. I have presented this as a small application with a main() method which can be run from the command line, although future query examples will be shown as code snippets. SimpleQuery.Java package com.ogilviepartners.jdobook.app; import java.util.Collection; import java.util.Iterator; import javax.jdo.*; public class SimpleQuery { public static void main() { JDOBootstrap bootstrap = new JDOBootstrap(); PersistenceManagerFactory pmf = bootstrap.getPersistenceManagerFactory(); PersistenceManager pm = pmf.getPersistenceManager(); Transaction t = pm.currentTransaction(); t.begin(); Extent partnerExt = pm.getExtent( BusinessPartner.class, true); Query q = pm.newQuery(partnerExt); Collection c = (Collection) q.execute(); Iterator i = c.iterator(); System.out.println( “Listing all BusinessPartner instances:”); while(i.hasNext()) { Object o = i.next(); System.out.println(o); } System.out.println(”Done.”); q.close(c); t.commit(); } } The above example is indeed very simple. There is no filter defined, nor are there any parameter, variable, import, or ordering declarations. The candidate

Hint: This post is supported by Gama web hosting hrvatska services

134 Queries with JDOQL Query compilation is generally

Saturday, October 28th, 2006

134 Queries with JDOQL Query compilation is generally recommended when the same query will be executed multiple times (albeit with different parameter values), or when queries are defined and then stored for later execution. 8.3.1 Query execution The following methods of the Query interface are used to execute a query, each with a different argument list for incoming query parameter values. The methods are all defined to return Object for flexibility in future enhancements to JDOQL. However, under the current version of JDO, all executions result in an unmodifiable collection object. The returned reference should be manually cast to collection by the application developer. Object execute() Object execute(Object p1) Object execute(Object p1, Object p2) Object execute(Object p1, Object p2, Object p3) Execute a query taking zero, one, two, or three parameters. Parameters are positional, and must be passed in the order in which they were declared. Object executeWithArray(Object[] parameters) Execute a query that takes any number of parameters (zero or more). Parameters are positional, and must appear in the array in the order in which they were declared in the query. Object executeWithMap(Map parameters) Execute a query that takes any number of parameters (zero or more). Parameters are named instead of positional . The map contains key and value pairs. Each parameter of the query will be assigned the value corresponding to the map entry with the parameter name as key. 8.3.2 Closing query results void close(Object queryResult) Close the resources associated with a given query result. void closeAll() Close the resources associated with all query results obtained from executions of this query. 8.4 Query examples Although we have yet to discuss the syntax of query filters, we are now in a position to examine some simple queries.

Hint: This post is supported by Gama web hosting hrvatska services