| By Thorick Chow | Article Rating: |
|
| September 23, 2002 12:00 AM EDT | Reads: |
12,686 |
The standard EJB 2.0 container- managed persistence (CMP) query language known as EJB QL allows users to retrieve container-managed entity beans, subject to constraints that are described using the same object-relationship model that was constructed to describe beans in EJB deployment.
With this language you can reduce large classes of search problems to the task of writing queries that can be expressed in a straightforward and natural manner.
Some classes of problems can't be solved using the capabilities of standard EJB QL, however. One such class can be described intuitively as "that class of problems for which a single scan of the retrieval candidates isn't enough to narrow down the beans that qualify to be selected." For example, suppose you have a set of beans that represent recordings. You want to find the set of recordings whose sales totals are above the average taken of all recordings. This isn't possible looking through the candidate data just once, because in order to know which recordings have above-average sales totals, you must first know what the average value is.
Answering this kind of question using EJB QL requires something extra. WebLogic 7 gives you that something extra with support for subqueries in EJB QL. This article will demonstrate different ways to harness the power of this new feature to answer previously unanswerable questions using EJB QL.
The example queries use the EJB CMP beans and relationship schema defined in the "Bands" example, which can be found in WebLogic Server Version 7 at RELEASE_DIRECTORY\samples\ server\src\examples\ejb20\relationships\bands.
The Bands example contains four entity beans: BandEJB, RecordingEJB, FanClubEJB, and ArtistEJB. Figure 1 illustrates the relationships between these beans.
The Structure of EJB QL Subqueries
As the name implies, a subquery is a query that's
subordinated within an outer query. As EJB QL is an SQL-like
language, the WebLogic EJB QL subquery (EJB QL subquery) syntax
resembles that of subqueries used in SQL. As in SQL, the EJB QL
subquery is used as an operand within the WHERE clause of an outer
query as a producer of values to be used by an operator.
Suppose you want to write the EJB QL for a finder that will return all the BandEJBs that meet the following criteria: for the years 1961 and later, find the bands that have released a recording that has sold more copies than the average number of copies per record sold of all recordings.
This type of search criteria can't be expressed using standard EJB QL because there's no provision for computing the average of the number of copies sold, nor is there a provision for comparing a particular recording's copies sold with the computed average. This query can be written utilizing the WebLogic EJB QL language extensions support for aggregate functions (AVG or Average in this case) and support for subqueries.
Listing 1 illustrates an EJB QL query that will evaluate the search criteria. (Listings 1-9 are available for download at www.sys-con.com/weblogic/sourcec.cfm.) There are a few things worth noting about this query:
The subquery selects all recordings recorded by all bands after December 31, 1960. The average is taken of the numberSold of all the recordings selected. The main query then qualifies a band for selection by requiring that a candidate band has a recording recorded after December 31, 1960, that has sold more copies than the average value previously computed by the subquery. The collection of qualified bands comprises the results of the query.
Correlated and Uncorrelated Subqueries
The query in the previous example is an uncorrelated
subquery. An uncorrelated subquery can be thought of as completely
self-contained. All identifier variables in an uncorrelated subquery
are scoped within the subquery. A subquery that contains references
to identifier variables declared by a parent query is referred to as
a correlated subquery. For example, consider a query to return
RecordingEJBs that meet the following criteria: find the records that
are in the top-three ranking by number sold; show these top three
records in descending order.
Listing 2 illustrates an EJB QL query that will return RecordingEJBs that meet this criteria. A few things about this query are worth noting:
Each RecordingEJB is considered to be a candidate by the main query. The value of "record.numberSold" for each candidate is passed down to the subquery. The subquery does its own scan of all the RecordingEJBs, counting the number that have a value "subquery_record.numberSold" that exceeds the value of "record.numberSold" passed in by the main query. If this number is less than three, there are at most two records in the entire set of RecordingEJBs that exceed the candidate. The candidate is in the top three, the the condition in the main query WHERE clause evaluates to "true", and the main query SELECTs the candidate.
This process is repeated by the outer query for each candidate until all the candidates are checked for qualification. The top three RecordingEJBs are then returned in descending order by numberSold.
This query is processed in a different manner than the previous example's uncorrelated subquery. Unlike the uncorrelated subquery in Listing 1, which is evaluated only once, this example's correlated subquery (shown in Listing 2) will be evaluated once for each row for which the outer query produces a value "record.numberSold". Since the correlated subquery is evaluated separately for each candidate produced by the main query, the performance cost of evaluating correlated subqueries is something to keep in mind when making decisions about using them.
Subqueries Returning Multiple Values
In each of the examples we've considered so far, the subquery
always returned a single scalar value. The operator that took the
subquery as a right-hand argument in both cases was the comparison
operator "greater than" (">") operator. This accepts only scalar
values from its right-hand operands. If you try to use a comparison
operator like ">" with a right-hand operand that returns multiple
values, a runtime error will be thrown by the underlying SQL engine.
Consider a query to return BandEJBs based on the following criteria: find the bands that have released any recording that has sold more units than the number of units sold of any recording before 1961.
Listing 3 shows one attempt at writing this query. In general, this query won't work - it's very likely that there was more than one recording recorded before 1961, and the ">" operator wouldn't be able to handle the resulting multiple-valued right-hand argument.
If Oracle were used as the underlying SQL engine, you'd receive the runtime SQL Exception: "ORA-01427: single-row subquery returns more than one row". Similarly, SQL Server would return the corresponding runtime SQL Exception: "Server: Msg 512, Level 16, State 1, Line 1 Subquery returned more than 1 value". This isn't permitted when the subquery follows =, !=, <, <= , >, >=, or when the subquery is used as an expression.
To fix this, use an operator that expects the subquery to return multiple values. In this case, follow the ">" operator with "ALL". The corrected query is shown in Listing 4.
This is an uncorrelated subquery, so it is evaluated first to find the set of all records recorded before January 1, 1961. The main query then considers a candidate band and a candidate recording from the candidate band. If the recording.numberSold exceeds the numberSold of the set of ALL records selected by the subquery, the main query SELECTs the band.
All the comparison operators {=, <>, <, >, <=, >=} expect their right-hand arguments to be single valued. If the subquery argument to any of these operators may return more than a single value, the appropriate qualifiers "ALL" or "ANY" should be appended after the comparison operator.
Subqueries that may return multiple values can also be used with the [NOT] IN and [NOT] EXISTS operators. To illustrate the use of [NOT] IN, let's suppose the legal department of a recording company wants to answer the following: find the names of all bands such that each returned band is named after the founder of a different band and the founder of the different band is not a member of the returned band.
Listing 5 illustrates a query that answers this question using the [NOT] IN operator in combination with a correlated subquery. Let's consider the workings of this query in detail. An examination of the FROM clause of the outer query reveals three separate range variable declarations - two that refer to the BandEJB and one that refers to the ArtistEJB. Two separate declarations for the BandEJB are required so we can distinguish between the two sets of bands that need to be compared. The identifier targetBand represents a band considered for inclusion in the final results, and the identifier founderBand represents a band whose founder a targetBand will have taken as its namesake. The identifier founderArtist represents the artist who is the founder of the founderBand. For example, suppose that the founderBand is "X" and that the name of the founder of X is "John Doe." The founderArtist will be the ArtistEJB representing John Doe, the founder of the founderBand X. The task of the query, then, is to locate any band named John Doe that doesn't include the artist named John Doe as a member.
At execution time, the outer query chooses a candidate band subject to criteria specified by its join between the targetBand and the founderBand: the name of a targetBand must be equal to the name of the founder of the founderBand John Doe. The subquery then takes the candidate band John Doe presented by the outer query, and selects the set of the IDs of all artists that are members of the band John Doe. The outer query checks whether the founderArtist ID for John Doe is [NOT] IN the set of artists that are members of the band John Doe that the subquery returned. If founderArtist ID for John Doe is [NOT] IN the set, the band John Doe is added to the set of bands that the main query will return. This procedure is repeated for all of the candidates the outer query chooses. The set of qualifying bands is returned as the final query result, and then the company legal department goes to work.
Consider the differences between the [NOT] IN operator and the [NOT] EXISTS operator. Where [NOT] IN is used to check whether its left-hand operand is contained within the set returned by its right-hand subquery operand, the [NOT] EXISTS operator has only a right-hand operand and checks whether the set returned by its right-hand subquery operand is empty or not. To illustrate the use of [NOT] EXISTS, Listing 6 shows the query of the previous [NOT] IN John Doe example rewritten to use the [NOT] EXISTS operator.
Standard EJB QL and Hidden Subqueries
Let's consider again the [NOT] IN John Doe query of Listing
5. You may notice that the question that led to the formulation of
this query could also have been expressed as a query using only
standard EJB QL with the help of the NOT MEMBER OF operator. Listing
7 illustrates an equivalent query using NOT MEMBER OF.
It's interesting to examine the SQL the EJB compiler generates for the NOT MEMBER OF query. The complete generated SQL is shown in Listing 8.
Of particular interest is that the EJB QL NOT MEMBER OF operator was translated by the EJB compiler into a database query using the SQL [NOT] IN operator operating on a correlated subquery. The EJB QL NOT MEMBER OF operator is actually a hidden [NOT] IN operator that uses a correlated subquery. Now consider the EJB QL [NOT] IN John Doe query of Listing 5 that contained the explicit correlated subquery. The generated SQL for this query is shown in Listing 9. Comparing the generated SQL for the EJB QL NOT MEMBER OF query of Listing 8 against the generated SQL for the EJB QL [NOT] IN query of Listing 9 reveals that the SQL is essentially identical. Therefore, to the underlying DBMS, the two queries are identical. Clearly, the query can be expressed more compactly in EJB QL using the NOT MEMBER OF operator.
At times it may be useful to opt for the use of explicit subqueries, even when they don't seem necessary at first. Consider the following: using MS SQL Server version 7 and a small set of test data, SQL Server's query analyzer has interesting things to say about the SQL query generated for the EJB QL NOT MEMBER OF query (translated into the [NOT] IN query of Listing 9) versus the generated SQL query of the equivalent EJB QL query rewritten using [NOT] EXISTS with an explicit subquery in Listing 6. SQL Server will perform the following major operations to evaluate the two queries:
1. EJB QL Query using NOT MEMBER OF with generated NOT IN
with subquery:
2. EJB QL Query using explicit NOT EXISTS with subquery:
In comparing the list of operations that SQL Server will perform to evaluate the [NOT] IN query versus the [NOT] EXISTS query, note that the [NOT] IN query will require five merges versus the [NOT] EXISTS query's four merges, two clustered index scans versus one clustered index scan, and one sort versus no sort. While the actual performance of SQL queries depends on many factors, the difference in the tally of operations in the query execution plans chosen by SQL Server illustrates that one query might be a better performer than the other. Thus, it may be advantageous to rewrite an EJB QL query that uses an operator like NOT MEMBER OF to instead use an explicit subquery. It must be noted that there's no general rule stating that the use of [NOT] EXISTS is more efficient than using [NOT] IN. The actual determination of which query style will be the better performer on which DBMS and under what conditions is the province of SQL performance tuning. What's important to remember is that with support for EJB QL subqueries, you have choices. This is especially important when dealing with SQL queries that involve correlated subqueries, which can be heavy users of DBMS resources.
For reference, Table 1 lists the standard EJB QL operators for which the EJB compiler may generate SQL with hidden subqueries.
The SQL generated by the EJB compiler can be examined by compiling the EJB with the "keepgenerated" option as in: java weblogic.ejbc -keepgenerated build\std_ejb20_bands.jar ejb20_bands.jar
The output jar file "ejb20_bands.jar" will contain generated Java source files for each EJB. For example the generated Java source file for the BandEJB will be: BandBean_lya094__WebLogic_CMP_RDBMS.java
This source file will contain the generated SQL for each finder and ejbSelect method run by that bean and can be examined with your favorite editor.
Summary
The introduction of EJB QL subqueries in WebLogic 7 gives you
the ability to write finder and ejbSelect methods that are capable of
satisfying an enriched set of search criteria over standard EJB QL.
Because the syntax of WebLogic EJB QL subqueries resembles the syntax
of SQL subqueries, the learning curve associated with EJB QL
subqueries is short and painless. In a manner similar to SQL, EJB QL
subqueries may be used as operands of the operators {{ =, <>, <, >,
<=, >=} [ANY | ALL], [NOT] IN, [NOT] EXISTS }. In addition to
answering questions that could not previously be answered, subqueries
provide the programmer options with regard to custom tuning of
standard EJB QL queries when those standard EJB QL queries make use
of hidden subqueries. Subqueries are a handy addition to the EJB
programmer's toolbox.
Enjoy the enhanced capabilities of WebLogic EJB QL with subqueries.
Published September 23, 2002 Reads 12,686
Copyright © 2002 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
More Stories By Thorick Chow
Thorick Chow is an Engineer at BEA Systems. After receiving his degree in Physics from the University of California at Berkeley in 1988, he joined the Client Server revolution at Sybase. In 1998 he joined the Java Application Server revolution at WebLogic where he has been involved in the development of WebLogic jDriver and WebLogic EJB products.
- The Economics of Cloud Computing Analyzed
- GovIT Expo Highlights Cloud Computing
- Cloud Computing Best Practices
- Tactical Cloud Computing Panel at 1st Annual GovIT Expo
- Why SOA Needs Cloud Computing - Part 1
- The Cloud Transition: What Does It Mean For You?
- Cloud Computing Strategy
- IBM’s Mainframe Monopoly Threatened by BMC Founder’s Shop
- Economy Drives Adoption of Virtual Lab Technology
- Virtualization Expo Call for Papers Deadline December 15
- Oracle in Leader's Quadrant for Enterprise Application Servers
- Oracle Fusion Middleware Delivers World Record Single-Node Result
- The Economics of Cloud Computing Analyzed
- The Difference Between Web Hosting and Cloud Computing
- GovIT Expo Highlights Cloud Computing
- Cloud Computing Best Practices
- Tactical Cloud Computing Panel at 1st Annual GovIT Expo
- Citrix Aims To Cripple VMware’s Cloud Designs
- Product Evaluation: JBoss TCO Calculator
- Why SOA Needs Cloud Computing - Part 1
- Build Reliability into Cloud Computing for SMBs
- Perhaps SOA is More Strategy Than Architecture
- EC Wrong, Wrong, Wrong – and Sloppy to Boot: Intel
- Five Reasons to Choose a Private Cloud
- Java vs C++ "Shootout" Revisited
- Where Are RIA Technologies Headed in 2008?
- Configuring Eclipse for Remote Debugging a WebLogic Java Application
- Migrating a JBoss EJB Application to WebLogic
- XA Transactions
- The Top 250 Players in the Cloud Computing Ecosystem
- An Introduction to Abbot
- WebLogic Tutorial: "Integrating Apache Poi in WebLogic Server"
- Eclipse "Pollinate" Project to Integrate with Apache Beehive
- Failover and Recovery of Enterprise Applications - Part 1
- Cover Story: A Practical Solution to Internationalization of a J2EE Web App
- WebSphere vs WebLogic: IBM and BEA Spar Over SPEC Results































