31.6.2. EJB-QL Declaration

Every select or finder method (except findByPrimaryKey) must have an EJB-QL query defined in the ejb-jar.xml file. The EJB-QL query is declared in a query element, which is contained in the entity element. The following are the declarations for findBadDudes_ejbql and ejbSelectBoss_ejbql queries:
<ejb-jar>
    <enterprise-beans>
        <entity>
            <ejb-name>GangsterEJB</ejb-name> 
            <!-- ... -->
            <query>
                <query-method>
                    <method-name>findBadDudes_ejbql</method-name>
                    <method-params>
                        <method-param>int</method-param>
                    </method-params>
                </query-method>
                <ejb-ql>
                 SELECT OBJECT(g) FROM gangster g WHERE g.badness > ?1
                 </ejb-ql>
            </query>
            <query>
                <query-method>
                    <method-name>ejbSelectBoss_ejbql</method-name>
                    <method-params>
                        <method-param>java.lang.String</method-param>
                    </method-params>
                </query-method>
                <ejb-ql>
                 SELECT DISTINCT underling.organization.theBoss FROM gangster underling WHERE underling.name = ?1 OR underling.nickName = ?1
                 </ejb-ql>
            </query>
        </entity>
    </enterprise-beans>
</ejb-jar>
EJB-QL is similar to SQL but has some surprising differences. The following are some important things to note about EJB-QL:
  • EJB-QL is a typed language, meaning that it only allows comparison of like types (i.e., strings can only be compared with strings).
  • In an equals comparison a variable (single valued path) must be on the left hand side. Some examples follow:
g.hangout.state = 'CA' Legal
'CA' = g.shippingAddress.state NOT Legal
'CA' = 'CA' NOT Legal
(r.amountPaid * .01) > 300 NOT Legal
r.amountPaid > (300 / .01) Legal
  • Parameters use a base 1 index like java.sql.PreparedStatement.
  • Parameters are only allowed on the right hand side of a comparison. For example:
gangster.hangout.state = ?1 Legal
?1 = gangster.hangout.state NOT Legal