Home > Articles > Programming > Java

  • Print
  • + Share This

The EJB Query Language (EJBQL)

You might have noticed that different EJB container vendors have different ways of defining the queries for finder methods. Some require you to specify an SQL query, while others have their own query languages. EJB 2.0 introduces a standard EJB query language so that you need to write your finder queries only one time. In fact, you now include your finder queries in the ejb-jar.xml deployment descriptor file instead of the vendor-specific deployment descriptor.

EJBQL is similar to SQL, so it's very easy to pick up. Basically, you define a WHERE clause and use ?1, ?2, ?3, and so on to represent the parameters for your finder method. For example, a finder method called findByLastName(String aLastName) might be defined with a query like this:

WHERE lastName = ?1

In your deployment descriptor, you define it this way:

<query>
    <query-method>
        <method-name>findByLastName</method-name>
        <method-params>
            <method-param>java.lang.String</method-param>
        </method-params>
    </query-method>
    <ejb-ql>
        <![CDATA[WHERE lastName like ?1]]>
    </ejb-ql>

</query>

As with SQL, you can use AND and OR to compare multiple fields, like this:

WHERE firstName = ?1 and lastName=?2

EJBQL has quite a few variations for more complex queries. You can locate objects based on values in related object and other interesting variations. The best part of EJBQL, other than the fact that it is so similar to SQL, is that it is standard across all EJB 2.0-compliant containers. You need to write the queries only once.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.