Welcome!

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.

    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.

  • 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 keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settle...
    Product connectivity goes hand and hand these days with increased use of personal data. New IoT devices are becoming more personalized than ever before. In his session at 22nd Cloud Expo | DXWorld Expo, Nicolas Fierro, CEO of MIMIR Blockchain Solutions, will discuss how in order to protect your data and privacy, IoT applications need to embrace Blockchain technology for a new level of product security never before seen - or needed.
    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...
    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 ...
    Imagine if you will, a retail floor so densely packed with sensors that they can pick up the movements of insects scurrying across a store aisle. Or a component of a piece of factory equipment so well-instrumented that its digital twin provides resolution down to the micrometer.
    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...
    When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
    We are given a desktop platform with Java 8 or Java 9 installed and seek to find a way to deploy high-performance Java applications that use Java 3D and/or Jogl without having to run an installer. We are subject to the constraint that the applications be signed and deployed so that they can be run in a trusted environment (i.e., outside of the sandbox). Further, we seek to do this in a way that does not depend on bundling a JRE with our applications, as this makes downloads and installations rat...
    Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
    DX World EXPO, LLC, a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
    In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
    Digital Transformation (DX) is not a "one-size-fits all" strategy. Each organization needs to develop its own unique, long-term DX plan. It must do so by realizing that we now live in a data-driven age, and that technologies such as Cloud Computing, Big Data, the IoT, Cognitive Computing, and Blockchain are only tools. In her general session at 21st Cloud Expo, Rebecca Wanta explained how the strategy must focus on DX and include a commitment from top management to create great IT jobs, monitor ...
    "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...
    The IoT Will Grow: In what might be the most obvious prediction of the decade, the IoT will continue to expand next year, with more and more devices coming online every single day. What isn’t so obvious about this prediction: where that growth will occur. The retail, healthcare, and industrial/supply chain industries will likely see the greatest growth. Forrester Research has predicted the IoT will become “the backbone” of customer value as it continues to grow. It is no surprise that retail is ...
    "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.
    SYS-CON Events announced today that Conference Guru has been named “Media Sponsor” of the 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great deals to gre...
    The Internet of Things will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform. In his session at @ThingsExpo, Craig Sproule, CEO of Metavine, demonstrated how to move beyond today's coding paradigm and shared the must-have mindsets for removing complexity from the develop...
    In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
    "Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
    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 ...