Weblogic Authors: Yeshim Deniz, Elizabeth White, Michael Meiner, Michael Bushong, Avi Rosenthal

Related Topics: Weblogic

Weblogic: Article

The Power of EJB QL Subqueries in WebLogic Server Version 7

The Power of EJB QL Subqueries in WebLogic Server Version 7

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's SELECT statement "SELECT AVG(subquery_records.numberSold)" makes use of WebLogic EJB QL language extension support for aggregate functions, the AVG() (i.e., average) function in this case. The subquery will return a single scalar value - the average of the numberSold field of the qualified subquery_records qualified by the subquery's WHERE clause.
  • The subquery (all the text between the enclosing parentheses in the first WHERE clause) is syntactically identical to a "normal" query. You could cut and paste the subquery and use it as the text of a complete query in itself (in an ejbSelect that returns the average number of units sold per recording, for example).
  • The identifier variables declared in the subquery's FROM clause are distinct. That is, the subquery range identifier variable "subquery_band" is distinct from the corresponding main query range identifier variable "band". Likewise, the subquery collection member identifier variable "subquery_records" is distinct from the main query collection member identifier variable "records". All the identifiers declared in all FROM clauses in a query and its subqueries must be unique.

    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:

  • In the subquery's WHERE clause, the ">" operator's left-hand operand "subquery_record.numberSold" contains the range identifier variable "subquery_record", which is declared in the subquery.
  • In the subquery's WHERE clause, the ">" operator's right-hand operand "record.numberSold" contains the range identifier variable "record", which is declared in the outer main query. This reference to a variable in the range of the outer query categorizes this subquery as a correlated subquery.
  • The main query uses the WebLogic EJB QL language extension "ORDERBY <path-expression-ending-in-cmp-field> DESC". The ability to specify descending order in an ORDERBY clause is a new feature in WebLogic 7.

    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:

  • Five merges
  • Two clustered index scans
  • One sort
  • One full table scan
  • Three clustered index seeks
  • One temporary table

    2.   EJB QL Query using explicit NOT EXISTS with subquery:

  • Four merges
  • One clustered index scan
  • Zero sorts
  • One full table scan
  • Three clustered index seeks
  • One temporary table

    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.

    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.

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

    Comments (0)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

    IoT & Smart Cities Stories
    In today's enterprise, digital transformation represents organizational change even more so than technology change, as customer preferences and behavior drive end-to-end transformation across lines of business as well as IT. To capitalize on the ubiquitous disruption driving this transformation, companies must be able to innovate at an increasingly rapid pace.
    Predicting the future has never been more challenging - not because of the lack of data but because of the flood of ungoverned and risk laden information. Microsoft states that 2.5 exabytes of data are created every day. Expectations and reliance on data are being pushed to the limits, as demands around hybrid options continue to grow.
    "MobiDev is a Ukraine-based software development company. We do mobile development, and we're specialists in that. But we do full stack software development for entrepreneurs, for emerging companies, and for enterprise ventures," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
    The explosion of new web/cloud/IoT-based applications and the data they generate are transforming our world right before our eyes. In this rush to adopt these new technologies, organizations are often ignoring fundamental questions concerning who owns the data and failing to ask for permission to conduct invasive surveillance of their customers. Organizations that are not transparent about how their systems gather data telemetry without offering shared data ownership risk product rejection, regu...
    The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
    Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
    When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
    Machine learning has taken residence at our cities' cores and now we can finally have "smart cities." Cities are a collection of buildings made to provide the structure and safety necessary for people to function, create and survive. Buildings are a pool of ever-changing performance data from large automated systems such as heating and cooling to the people that live and work within them. Through machine learning, buildings can optimize performance, reduce costs, and improve occupant comfort by ...
    Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
    With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...