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.

    @ThingsExpo Stories
    In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
    It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
    Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
    "Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
    "Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
    "MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
    SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
    "There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
    "IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
    WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, introduced two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a multip...
    SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
    Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
    SYS-CON Events announced today that Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
    Leading companies, from the Global Fortune 500 to the smallest companies, are adopting hybrid cloud as the path to business advantage. Hybrid cloud depends on cloud services and on-premises infrastructure working in unison. Successful implementations require new levels of data mobility, enabled by an automated and seamless flow across on-premises and cloud resources. In his general session at 21st Cloud Expo, Greg Tevis, an IBM Storage Software Technical Strategist and Customer Solution Architec...
    A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
    To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
    An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics gr...
    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, it’s about the data consumed and generated. The devices are tools, mechanisms, conduits. In his session at Internet of Things at Cloud Expo | DXWor...
    Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution. In his session at @ThingsExpo, Akvelon expert and IoT industry leader Sergey Grebnov provided an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
    SYS-CON Events announced today that Synametrics Technologies will exhibit at SYS-CON's 22nd International Cloud Expo®, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Synametrics Technologies is a privately held company based in Plainsboro, New Jersey that has been providing solutions for the developer community since 1997. Based on the success of its initial product offerings such as WinSQL, Xeams, SynaMan and Syncrify, Synametrics continues to create and hone inn...