Archive for October, 2006

132 Queries with JDOQL Query newQuery(Class cls, Collection

Saturday, October 28th, 2006

Query interface 133 I will describe each of the Query interface s methods briefly before we look at our first JDOQL examples. PersistenceManager getPersistenceManager() Returns a reference to the persistence manager with which the query is associated. void setClass() Sets the candidate class for the query. void setCandidates(Collection candidateCollection) Sets the candidate collection for the query. void setCandidates(Extent candidateExtent) Sets the candidate class and candidate collection for the query, from the values encapsulated in the Extent. void setFilter(String filter) Sets the filter criteria for the query. The filter should be valid according to the chosen query language. void declareImports(String imports) Provides an import declaration. This will import classes into the type name- space, so that these types can be used for the declaration of query parameters and variables. void declareVariables(String variables) void declareParameters(String parameters) void setOrdering(String ordering) Provide the variable, parameter and ordering declarations for the query. void setIgnoreCache(boolean ignoreCache) Boolean getIgnoreCache() These methods access the value for the IgnoreCache query property. If the property is set to true, the query might be executed such that changed instances in the persistence manager cache but not yet committed to the data store are ignored, and the currently persistent versions of those instances are queried instead. This may improve query execution speeds with some JDO implementations, at the expense of generating only approximate query results. As such it should probably be applied only to read-only transactions, within which data is queried but never altered. void compile() JDOQL does not require queries to be compiled. However, compilation of queries has two advantages. Firstly, any syntactic errors can be reported in advance of query execution. Secondly, a compiled query may execute more quickly than an uncompiled equivalent, although this is entirely implementation-dependent.
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services

132 Queries with JDOQL Query newQuery(Class cls, Collection

Saturday, October 28th, 2006

132 Queries with JDOQL Query newQuery(Class cls, Collection cln, String filter) Construct a new query with the specified candidate class, candidate collection, and filter expression. The collection may contain zero or more objects, all of which must be instances of the candidate class. Query newQuery(Extent cln, String filter) Construct a new query with the candidate class derived from the Extent, a candidate collection comprised of all persistent instances of the Extent, and the specified filter expression. Query newQuery(Class cls, String filter) Construct a new query with the specified candidate class and filter expression. 8.3 Query interface The object returned from the query factory methods of a persistence manager is an instance of the Query interface. The UML for the Query interface is shown in Figure 8.1. interface Query java.io.Serializable +setClass(cls:Class):void +setCandidates(pcs:Extent):void +setCandidates(pcs:Collection):void +setFilter(filter:String):void +declareImports(imports:String):void +declareParameters(parameters:String):void +declareVariables(variables:String):void +setOrdering(ordering:String):void +setIgnoreCache(ignoreCache:boolean):void +getIgnoreCache( ):boolean +compile( ):void +execute( ):Object +execute(p1:Object):Object +execute(p1:Object,p2:Object):Object +execute(p1:Object,p2:Object,p3:Object):Object +executeWithMap(parameters:Map):Object +executeWithArray(parameters:Object( )):Object +getPersistenceManager( ):PersistenceManager +close(queryResult:Object):void +closeAll( ):void Figure 8.1 UML for Query interface
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services

130 Queries with JDOQL The philosophy of JDOQL

Saturday, October 28th, 2006

Constructing queries 131 . Identifier Namespace. All parameter names, variable names, and persistent field names reside in this namespace. The persistent field names include all persistent fields of all classes referenced in the query. Thus it is not legal to define a parameter or variable with the same name as a persistent field of the candidate class or other persistence-capable class referenced in the query. Nor is it legal to define both a parameter and a variable with the same name. JDOQL is very Java-like in syntax and therefore easy for Java developers to master. Nevertheless, the query interface has been designed so that it can be used with an alternative query language if the application so chooses, presuming that this alternative language is supported by the implementation. 8.2 Constructing queries A persistence manager acts as the factory for queries, and provides a set of newQuery() methods by which an application can construct queries. These methods are detailed below. Query newQuery() Constructs a new query instance, bound to the current persistence manager. All of the query s properties can then be set directly, including the query language. Query newQuery(Object query) Constructs a query instance from another query. The new query shares the original query s elements except for the candidate collection or extent. The new query is bound to the persistence manager on which newQuery() was executed, even though the original query may have been obtained from a different persistence manager. This, combined with the requirement that all query implementation classes are serializable, facilitates the construction of a new query based on one earlier constructed against a different JDO implementation. This method presumes that the implementation s default query language (typically JDOQL) is to be used. Query newQuery(String language, Object query) Constructs a new query from an existing query using the specified query language. Query newQuery(Class cls) Construct a new query with the specified candidate class. Query newQuery(Extent cln) Construct a new query with the candidate class derived from the Extent, and a candidate collection comprised of all persistent instances of the Extent. Query newQuery(Class cls, Collection cln) Construct a new query with the specified candidate class and candidate collection. The collection may contain zero or more objects, all of which must be instances of the candidate class.
Note: If you are looking for good and quality webspace to host and run your java application check Actions java hosting services

130 Queries with JDOQL The philosophy of JDOQL

Saturday, October 28th, 2006

130 Queries with JDOQL The philosophy of JDOQL revolves around the concept of a so-called candidate collection of instances to which the query s filter criteria will be applied. The result of query execution is an unmodifiable Collection, comprised of those members of the candidate collection for which the filter criteria evaluated to true. Queries can include parameterized values. They can also define and use local reference variables to which values are assigned during query execution, and by which the query filter may traverse connected instances. Queries consist of the following mandatory elements: . The candidate class. All instances of the candidate collection will be instances of this class. The unmodifiable collection returned after query execution will contain only instances of the candidate class. Polymorphism is fully supported, so instances of implicitly includes any subclasses of the candidate class. . The candidate collection. This may be a true Collection object containing zero or more objects, all of which must be instances of the candidate class. Alternatively this may be the Extent of the candidate class, implicitly including all persistent instances as candidates for the query. (The extent may optionally include or exclude subclasses of the candidate class.) . The query filter. This is expressed as a Java-like boolean expression. The result of query execution will include only those candidates for which the expression evaluates to true. Queries may additionally contain: . parameter declarations, comprising one or more pairs of identifier names and types; . parameter values, provided at execution time, which are bound to the declared parameter identifiers. Values are usually assigned to declared identifiers as positional parameters, but can also be passed as named parameters depending on the application s requirements; . variable declarations, comprising one or more pairs of identifier names and types. Variables are typically used to hold references that allow query filters to span graphs of connected instances; . import declarations, used to import non-standard class names that are to be used as types for parameters or variables; . an ordering specification allowing arbitrary ordering of the query results. Queries also include the notion of namespaces. A given identifier name may not be defined more than once in a particular namespace. There are two name- spaces for each query: . Type Namespace. All type names used by the query reside in this namespace. Thus a query may not use two different types that have the same name. The candidate class and all public types in the java.lang package are implicitly imported into this namespace. Other types must be imported explicitly as required through the import declaration for the query.
Note: If you are looking for good and quality webspace to host and run your java application check Actions java hosting services

128 Transaction management JDOUserException, the transaction will be

Friday, October 27th, 2006

Queries with JDOQL JDO s transparent persistence allows applications to navigate through the persistent fields of an instance that are references to other persistent instances. As the application de-references these objects, those that are not present in the persistence manager s cache are loaded from the data store. This gives the application the impression that the entire inter-connected graph of persistent instances is immediately available in memory. The issue remains as to how an application should obtain the first persistent instance. Three methods are available. 1 The application can use the persistence manager s getObjectById() method if it is able to construct the Object ID instance. The Object ID may have been previously stored by the application for this purpose. Alternatively, an instance of the Object ID for a class with application identity may be constructed based on data input by the user. This is the most efficient way to retrieve a single specific instance. 2 The application could obtain an Iterator from the Extent of a persistence-capable class and iterate through the persistent instances. This approach might be used when it is the application s intention that every instance be processed. However, it is probably inefficient when trying to retrieve a single specific instance or a small group of instances. 3 The application can employ the Query interface and the new JDOQL. This employs a Java-like syntax for query definition, allowing the developer to specify filter criteria. Queries are implemented using the most efficient execution methods available in the target data store. This chapter describes JDOQL in detail. 8.1 Query architecture The JDO specification provides the Query interface and the JDOQL Query definition as an object-oriented and data-store independent means for the definition and execution of queries. By utilizing these features, application query requirements can be met without compromising the portability of the application amongst different implementations. JDOQL is intended to be neutral to the native query language of the underlying data store. Most implementations will map the elements of JDOQL into the data store s native query language. Of course, some data stores do not have their own query language, e.g. file systems and XML documents, and in such cases the implementation will have to provide client-side query execution functionality.
Note: If you are looking for top 10 and very good webhost to host and run your jsp application check Actions jsp hosting services

128 Transaction management JDOUserException, the transaction will be

Friday, October 27th, 2006

128 Transaction management JDOUserException, the transaction will be rolled back. The method is not called if a rollback is instigated instead of commit. The synchronization object s afterCompletion(int status) method will be called once the transaction is complete. The status parameter indicates the success or failure of the transaction, and will have one of two values: javax.transaction.Status.STATUS_COMMITTED javax.transaction.Status.STATUS_ROLLEDBACK Validation during commit There are two different ways in which instances may be validated before they are committed to the data store. The first is to have the instances implement the InstanceCallbacks interface, and perform the validation in the jdoPreStore() method. The second is to register a callback object using the transaction interface s setSynchronization() method, and to perform the validation from its beforeCompletion() method. I am not particularly in favor of the first approach, since it is less than transparent to the domain object model; the InstanceCallbacks interface is specific to JDO. Also, the jdoPreStore() method may be called multiple times on one instance in a single transaction, as it is invoked whenever the implementation flushes data to the data store. Use of synchronization objects may seem to be an easy alternative. However, the synchronization object must maintain a list of dirty instances to be validated. Instances may be involved in other transactions where no synchronization object is registered, and so critical validation cannot be guaranteed in this way. For the time being, therefore, jdoPreStore() may actually be the better of the two alternatives. This is an area that will be the subject of much debate as JDO becomes more widely used. I anticipate that, in a future version of JDO, persistence descriptor tags will be defined to provide declarative support for validation. These may include Delete Restrict and Delete Cascade functionality, as well as the identification of a validation method for each persistence-capable class, to be automatically invoked on instances during the commit process. What s next? In the next chapter, I introduce the new query language, JDOQL, which provides a Java-like syntax for the efficient querying of persistent data through JDO.
Note: If you are looking for top 10 and very good webhost to host and run your jsp application check Actions jsp hosting services

126 Transaction management If the NontransactionalWrite flag on

Friday, October 27th, 2006

Synchronization with JDO transactions 127 Improving upon RetainValues As it is currently defined, RetainValues applies globally to the entire contents of the persistence manager s cache. There is scope for this concept to be improved in future versions of JDO, so that instances of some specific persistence-capable classes can be retained but not others. Persistence-capa ble classes that represent infrequently changed reference data could then be retained in the cache, in order to reduce unnecessary data store access. A more advanced specification could facilitate timeouts for instances cached in this manner, so that the data store would indeed be checked if the instance was accessed after the designated period had elapsed. 7.6 Synchronization with JDO transactions It is sometimes useful for an application to be notified when a transaction is about to be committed or has been completed (successfully or not). The transaction interface facilitates this by providing for the registration of a user-provided callback object. The callback object must implement the javax.transaction.Synchronization interface. Its beforeCompletion() and afterCompletion() methods will be called to notify the application of these events. The synchronization interface is shown in Figure 7.2. interface javax.transaction.Synchronization +afterCompletion(:int):void +beforeCompletion( ):void Figure 7.2 UML for javax.transaction.Synchronization interface An instance of an application class that implements the Synchronization instance may be registered for transaction callbacks via the Transaction interface s setSynchronization() method. setSynchronization(javax.transaction.Synchronization sync) Replaces the previously registered synchronization object with the object sync. If the reference is null, then no object will receive transaction completion callbacks. The synchronization object s beforeCompletion() method will be invoked during the transaction s commit processing. If the method throws a
Note: If you are looking for top 10 and very good webhost to host and run your jsp application check Actions jsp hosting services

126 Transaction management If the NontransactionalWrite flag on

Friday, October 27th, 2006

126 Transaction management If the NontransactionalWrite flag on a Transaction is true, then the field values of Persistent-Nontransactional instances can be updated without an active transaction. Each of these capabilities is an optional feature in the JDO specification. 7.5 Transaction modes to improve efficiency JDO defines two additional transaction modes intended to improve efficiency. These are RestoreValues and RetainValues. Note that the setting of these flags only affects instances in memory, and does not alter the effect of commit or rollback processing on the data store. 7.5.1 RestoreValues The setting of the RestoreValues flag affects the treatment of instances in memory as a result of transaction rollback. If the RestoreValues flag is true, instances involved in a transaction that is rolled back will have their field values restored to their original values. These were cached when the transaction was begun. If the RestoreValues flag is false, instances involved in a transaction that is rolled back will be transitioned to Hollow. In such a state they do not have field values loaded, and thus the field values do not need to be restored to their original values. This allows JDO vendors to optimize their implementations so that instance values are not cached in the first place. If the now Hollow instance is accessed by the application, persistent fields will be loaded from the data store at that time. Setting RestoreValues to false can yield significant performance improvements if your application does not refer to instances after transaction rollback. 7.5.2 RetainValues This flag determines what action is taken by the persistence manager on persistent instances in memory after a transaction has been successfully committed. If RetainValues is false (the default setting), instances are automatically evicted on transaction commit, transitioning to Hollow. This limits the size of the instance cache and improves performance. If RetainValues is true, this automatic eviction does not take place. The persistent instances remain cached in the Persistent-Nontransactional state until they are once again used transactionally, or evicted. Eviction may be performed explicitly by the developer, or implicitly by the persistence manager to free up cache resources. This setting can improve performance of applications that work with the same set of instances across a number of independent transactions, at the expense of greater resource utilization by the persistence manager.
Note: If you are looking for top 10 and very good webhost to host and run your jsp application check Actions jsp hosting services

124 Transaction management 7.3.3.2 Reacting to optimistic concurrency

Thursday, October 26th, 2006

Advanced transaction options 125 Now we see the problem. A JDOUserException is thrown by the JDO implementation when the commit of the optimistic transaction was attempted. I presume that the application will redisplay the data and invite User1 to make his changes again (manual resolution). When the fields of the Hollow instance are read and displayed, the values will be retrieved from the data store, and the description Red Tables will be shown. However, the Persistent-Nontransactional instance will likely yield an outdated description of Green Tables. Thus, in response to an optimistic transaction failure, the user is being presented with transactionally inconsistent data. (This specific problem arises when an instance is read in an optimistic transaction and is not altered within that transaction, but is altered by another transaction.) Some implementations may choose to invalidate all instances involved in a failed optimistic transaction, essentially making them Hollow. This is not strictly correct, but as has been illustrated above would be extremely helpful. 7.3.4 Resolution using explicit refresh The solution to the quandary described above is to explicitly refresh each instance involved in an optimistic transaction failure before the data is redisplayed to the user. Unfortunately there is no means to achieve this automatically through the JDO API, which requires the application to maintain a list of instances involved in an optimistic transaction expressly for this purpose. Since the code which handles commit failures may not be part of the code that manipulates instances within the transaction, this problem may be non-trivial. Most of the JDO vendors agree that optimistic transactions are under-specified in JDO, and will be adding additional API calls to handle cases such as this. No doubt a future version of JDO will combine their best efforts under a revision of the standard API. 7.4 Advanced transaction options We now look at ways in which applications can access persistent data outside the context of an active transaction. Recall that persistence and transactionality can be applied to instances in any combination. We say that the two concepts are orthogonal; just because the instance is persistent does not mean that it is necessarily transactional. 7.4.1 NontransactionalRead and Write If the NontransactionalRead flag on a Transaction is true, then the field values of Hollow and Non-transactional instances can be read without an active transaction.

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

124 Transaction management 7.3.3.2 Reacting to optimistic concurrency

Thursday, October 26th, 2006

124 Transaction management 7.3.3.2 Reacting to optimistic concurrency assumption failures The premise of optimistic transactions is that the data probably will not change during the transaction. The risk of this happening is justified by the increased concurrency afforded by an optimistic strategy. Occasionally, however, the data associated with an optimistic transaction is changed by another (optimistic or pessimistic) transaction. The application must be able to cope with this. Highly evolved applications may attempt some form of data reconciliation, essentially merging changes with the now updated persistent instance values. However, such strategies are inherently complex, and their implementation depends heavily on the business domain being modeled. The simplest form of resolution involves telling the user their changes could not be saved and must be done again. The instances are refreshed from the data store, and these values are presented to the user. 7.3.3.3 Example without explicit refresh Before we consider the mechanics of such a policy, let us closely examine the intricacies of optimistic transaction failure. For this purpose, presume that we are working with the Product class. Our transaction will update the description field. To start with, presume we have two products: one with a description of Green Chairs and the other Green Tables. We are going to examine the potential conflict of two transactions. For ease of reference we will refer to two users, User1 and User2, although the issue also pertains to situations where a single user has multiple transactions simultaneously active through different persistence managers in the same JVM. User1 starts an optimistic transaction within which both products, Green Chairs and Green Tables, are read. The instances will transition Persistent- Nontransactional at this point since they have been read in an optimistic transaction. User1 now goes to lunch without completing the transaction. User2 begins a new transaction optimistic or pessimistic, it doesn t matter which. Both products are read and their descriptions updated to Red Chairs and Red Tables respectively. The transaction is committed, and the commit is successful. The persistent data has now been changed. User1, having returned from lunch, changes the description of the second product to Blue Tables. That instance transitions to Persistent-Dirty. By pressing the Save button (imagine a carefully crafted Swing interface if you will!), the transaction commit is attempted. However we know that the transaction will fail, as the underlying data store entities have been altered by another transaction. According to the state transition tables of the JDO specification, the dirty instance will transition back to Hollow. Note that, according to the same state tables, the unaltered instance remains in the Persistent-Nontransactional state.

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