EJB QL is used to express queries for the
find methods defined in an EJB's home interface and perform internal
select methods defined on the entity bean class. EJB QL queries contain a SELECT clause and a FROM clause, and optionally a WHERE clause. The query is placed in an application's ejb-jar.xml file.
The following XML code (defined in your jaws.xml file) maps a query to a
findByState method in the UserEJB's Home interface. The UserEJB sample application uses this query and method to find the user that corresponds to a given state.
<entity>
...
<query>
<query-method>
<method-name>findByState</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<ejb-ql>
[!CDATA[
SELECT DISTINCT object(u)
FROM UserEJB u
WHERE u.STATE = ?1]]
</ejb-ql>
</query>
</entity>
Referring to the preceding query definition, the
ejb-ql element defines the actual query that will be used. The OBJECT keyword is required when returning a single object type. Parameterized queries, as shown above, are facilitated with the use of logical numbered placeholders. Each number represents a parameter in the method's parameter list, starting from an index of 1.
In the example above, the number 1 will be replaced by the state parameter in the
findByState method. Entity beans that employ CMP can define a
findAll and/or a
findByPrimaryKey method, which will be implemented and executed transparently by the EJB container.
The EJB QL Query in Action
In
Listing 5, the
getUsersByState method is defined in the UserService class. This method makes a call to the
findByState method on the home interface of UserEJB. The EJB container will intercept the call and execute the query defined in the jaws.xml file.
The architectural differences between Java object hierarchies and relational database tables make the task of persisting Java object data to and from relational databases quite daunting for developers. The "impedance mismatch" between relational tables and Java object hierarchies has led to the development of several different object-persistence technologies attempting to close the gap between the relational world and the object-oriented world. The Enterprise JavaBeans framework defines a container-managed persistence mechanism, which has given programmers a tool that can simplify this problem, when used with the proper amount of care.