New Query Language Features of jdo2.0

Source: Internet
Author: User
New Query Language Features of jdo2.0

David Jordan

(Original: http://jdocentral.com/JDO_Articles_20040329.html)

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.
  • Indicates the value of a candidate or referenced field, such as address. Street. Name.
  • Field expression, which indicates the result of several arithmetic operations predefined by JDO on multiple fields.
  • Variable, representing an intermediate variable in the query Condition
  • Reference expression, that is, reference between objects in jdo1.0 through the "." Operator
  • Statistical expression

By combining these results expressions, you can obtain any expected results.

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)
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.

David Jordan created the Object Identity company to provide JDO consulting, training and software project customization and development services. He was an activist who joined the JDO Expert Group since its establishment. David Jordan and Craig Russell collaborated on the compilation of the authoritative Java Data Objects, which was published by o'reilly & Associates.

The copyright of this translation belongs to the author, but you are welcome to repost it on the premise that the source and original author are indicated. In additionMy columnView my other articles and provide valuable comments!

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.