Features of the JDO 2.0 query language for Java Data Objects

Source: Internet
Author: User

The improvement of the query language is an important part of the JDO2.0 specification. This article describes some new functions provided by JDO2.0 from a higher level. As the JDO2.0 specification has not yet entered the public draft State, nothing has been finalized yet, And everything may be subject to changes. However, JDO2.0 will soon enter the final stage, and the query feature mentioned here is that the JDO2.0 Expert Group (Translator's note: David Jordan is an important member of the Expert Group) takes the most time and is relatively stable. Therefore, I have enough reason to believe that the final Specification will be basically consistent with the description here.

If you think this article misses some important features, it is recommended to go To the JDO Forum immediately (http://www.jdocentral.com/forums/index.php? Showforum = 10. Here, we would like to thank Craig Russell, the leader of JDO2.0 standards, for authorizing me to publish the new features of these JDO2.0 query languages.

  Query Result

Let's start with the most in-depth improvements. In JDO1.0, the query result is always a set of instances of the class you specified. Consider the following UML class diagram, which expresses the relationships between four classes A, B, C, and D:

You can create A query for Class A, reference it to Class B through contains (), reference it to class C through another layer of contains (), and then use A ". class D. However, the returned collection only contains the object instance of Class A. If you want to obtain other classes from the result, you must use the reference of Class A to obtain relevant other class objects one by one. If your query conditions contain constraints of Class B, Class C, or Class D, when other class objects are referenced through class A objects in the result set, you must repeat these constraints in Java code. That is to say, you have to declare the constraints repeatedly in Java and JDOQL. Furthermore, you may only care about class D objects that meet the query conditions, rather than creating class B and class C objects in the middle by the JDO underlying layer to save memory or related resources.

In JDO2.0, you are no longer bound to these restrictions. You can return:

One or more fields of the Data class (PersistentCapable)
Other class objects other than candidate classes
Statistical data

This means that you can return A, B, C, D class objects, some of their fields, or the mixed results of the two. You can also calculate statistical results such as min or max. Basically, you can return any result.

When creating a query, you can specify a "Result Specification" to specify the returned content. It is a "Result Expression" that contains one or more comma-separated results )". The result expression can be:

This keyword indicates that the object instance of the candidate class is returned. This is the same as JDO1.0, indicating the value of a candidate or referenced field, such as address. street. name field expression, representing the result variable obtained by performing several arithmetic operations predefined by JDO on multiple fields, representing an intermediate variable reference expression in the query condition, in JDO1.0, the reference statistical expression between objects carried by the operator can get any result you want by combining the above result expressions.

JDO2.0 supports the following statistical functions:

Count (expression), the expression can be this
Sum (numeric field expression). "numeric field expression" can be a numeric result obtained through calculation of fields or fields.
Min (numeric field expression)
Max (numeric field expression)
Avg (numeric field expression)

The query result is specified through the following API:

Void javax. jdo. Query. setResult (String result)


If you do not call this method or the parameter is null, the system returns the object instance of the candidate class (equivalent to "this"), that is, the result returned by JDO1.0. If you only specify a unique result expression, the element type of the returned set is the same as that of the result. In addition, if multiple result expressions are specified by default, the returned set element type is Object [].

You can mark distinct at the beginning of the result definition string to ensure that the results are not duplicated. If the result definition string contains several expressions, distinct ensures that no duplicate data groups exist in the result set.

You can specify a name for each result expression. For a simple field, the system uses the name of this field as the name of the item in the result by default. For complex expressions, you can use the following syntax to specify the name:

Result_expression as name

  
The name can be set and used as an attribute in the result class. You can specify a result class to return the query results. If the query result is a single value, the result class can be any classes supported by JDO (Integer, Double, String, BigInteger, BigDecimal, java. util. date, java. SQL. date, java. SQL. time, java. SQL. timestamp ). The method for setting the result class in Query is as follows:

Void setResultClass (Class resultClass)


If the query result contains multiple result expressions, you can define a result class to retain the data in the result. This class must have a non-parameter constructor. In addition, each result expression must correspond to an attribute in this class, whether it is a public field or a public setXxx () method, in addition, the direct or bean-style attribute names are consistent with the results expressions in the query results.

Grouping)

The statistics function can be used in a group operation. JDO2.0 provides clauses similar to group by and HAVING clauses in SQL. Query Method:

Void setGrouping (String groupSpec)

The rule used to specify a group. The groupSpec parameter contains one or more grouping expressions separated by commas (,). It can also keep up with a filtering condition starting with "having. After this method is called, each result expression item of the setResult () parameter must be one in groupSpec or one or more operation results in groupSpec. Results With the same value for all groupSpec items are grouped into the same group (same result record ). The filtering condition of the having clause can contain a boolean result judgment statement or a statistical operation on the grouping expression. Like SQL, The having clause is used to filter the results set after grouping.

   Uniqueness)

Many people have been wondering why the execution (execute) result of Query is an Object type Object, which makes it inconvenient for developers to manually convert the result to Collection. The Query results in JDO1.0 generally have multiple elements, but the JDO Expert Group plans to add support for the Query that returns the single-value results in JDO2.0, so the Query execution result is defined as the Object type.

You sometimes execute a query with only one result (for example, counting the total number or searching for objects by a member account with a unique index). In JDO2.0, you can call the Query method to declare:

Void setUnique (boolean unique)

After "true" is passed in, the Query execution result is a separate value object. If no result is returned, the result is null. If JDO finds that multiple records are returned in the query results, an exception is thrown.

   Limit the size of returned results

When designing a user interface, we often display a subset of the result set (for example, display by page or only the first 10 ). For performance and efficiency, you may need to limit the range of returned results. The Query method can accomplish this:

Void setRange (int fromInclusive, int toExclusive)

The result set returned by this method only contains the fromInclusive to the toExclusive-1 of the original result set.

   New Filter condition Operators

Some new operators are added to JDOQL for reference, Map, string, and number operations. The instanceof operator returns a boolean value that allows you to filter objects of a specified class. Similarly, the containsKey (Object) function and containsValue (Object) function that return the boolean value are used to access the Map element.

Many functions are added for string processing. toLowerCase () and toUpperCase () are used to convert the case sensitivity. The following functions are also used to locate and obtain the substring:

Int indexOf (String)
Int indexOf (String, int) String substring (int, int)

In addition, the String method:

Boolean matches (String pattern)

Used to perform regular expression matching. Currently, only limited matching functions can be provided. "." And ". *" can represent wildcards, while "(? I) "indicates that the matching is case insensitive.

For numeric fields, JDO2.0 adds two functions:

Math. abs (numeric) Math. sqrt (numeric)

   Predefine query (Named Queries)

You can declare common JDOQL query statements in the JDO Descriptor (metadata), so that you do not need to embed the query into the Java source code. This provides some flexibility. For example, you can write a query statement to a configured text file, but you can directly modify the file when you need to modify it without changing the Java source code. Each query in the descriptor has a name. to execute a query, you can use the following method to create a query:

Query newNamedQuery (Class cls, String queryName)

JDO searches for the descriptor to find the corresponding predefined Query statement and generates the corresponding Query object.

   Access static fields (static fields)

You can access the constants declared in the public static final method in the data class in JDOQL. For example

Public static final int FEMALE = 0;
Public static final int MALE = 1;
Public static final int UNKNOWN = 2;

In the query, filter conditions similar to "salary> 5000.0 & gender = MALE" are used.

   Batch Delete (Deletion by Query)

In JDO1.0, to delete an object, you must load it into the memory before deleting it. However, in many cases, you do not need to access this object before deleting it. This method is inefficient. In JDO2.0, several Query methods are provided to delete a group of objects that meet the Query conditions:

Object deletePersistentAll (Object [] parameters) Object deletePersistentAll (Map parameters) Object deletePersistentAll ()

All objects in the query result will be deleted from the database. These methods return the set of deleted objects. Your program can decide whether to access the deleted objects one by one. If you do not access these objects, the Query execution performance will not be affected. In other words, these objects will not be generated in the memory.

Query features extended by vendor

JDO vendors can provide various special query functions for JDOQL. Each vendor can define a set of extensions of the vendor. If you need to use the functions, you need to add the vendor's extensions to the running environment. Each extension has a name and an optional value. You can set each extension separately or multiple extensions at a time. The following Query methods are used to set vendor extension features:

Void setExtensions (Map extensions) void addExtension (String key, Object value)

   Direct SQL access

If the query function of JDO2.0 cannot meet the requirements, and the following conditions are met:

Your application runs on a relational database.
  
You can use SQL statements to query

You know the ing details from your class model to the database

You can create an SQL query by calling the PersistentManger method:

Query newQuery (String language, Object query)
  
Each parameter must be set to "javax. jdo. query. SQL", and query is a specific SQL statement. If your query needs to return an instance of the class, the SQL statement must return the corresponding primary key field of the class. When a direct SQL statement is used, functions provided by JDOQL cannot be used. Otherwise, an exception JDOUserException is thrown. For example, you cannot set a filter condition string, sort statement, or variable Declaration for the Query. When SQL queries are used, the parameter types are not specified. And are bound in the order of appearance.

   Conclusion

As you can see, JDO2.0 has added many new functions and features for query statements. I think the definition of query results is the biggest improvement. As I mentioned at the beginning of this article, this change is currently the most stable part of JDO2.0 and will not change much. Vendors can start to provide many of these features without considering how the rest of JDO2.0 will change.

On the premise that JDO2.0 provides standard Object/link ing, the query function described here is a detach/attach mechanism for a multi-layer structure JDO application, JDO will occupy more markets. Vendors with deep understanding of this point will spare no effort to take the lead in launching stable, complete, and efficient JDO2.0 products. JDO is the first API for application development based on database storage and management. Developers will enjoy the object-oriented model design and efficient data storage management system.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.