EJB 3.0 QL Tutorial WWW - Sycorax.co - in
EJB 3.0 QL Tutorial WWW - Sycorax.co - in
0 QL Tutorial
www.sycorax.co.in
EJB QL and native SQL queries are executed through the javax.persistence.Query
interface. The Query interface is very analogous to the java.sql.PreparedStatement
interface. This Query API gives you methods for paging your result set, as well as passing Java
parameters to your query. Queries can be predeclared through annotations or XML, or created
dynamically at runtime through EntityManager APIs.
Query API
query in Java Persistence is a full-blown Java interface that you obtain at runtime from the entity
manager:
package javax.persistence;
package javax.persistence;
1
EJB 3.0 QL Tutorial
www.sycorax.co.in
try {
Query query = entityManager.creatQuery(
"from Customer c where c.firstName='Bill' and
c.lastName='Burke'");
Customer cust = (Customer)query.getSingleResult( );
} catch (EntityNotFoundException notFound) {
} catch (NonUniqueResultException nonUnique) {
}
The query is executed when the getSingleResult( ) method is called. This method expects
that the call will return only one result. If no result is returned, then the method throws a
javax.persistence.EntityNotFoundException runtime exception. If more than one result
is found, then a javax.persistence.NonUniqueResultException runtime exception is
thrown. Since both of these exceptions are RuntimeException s, the example code is not
required to have a full try/catch block.
You can change the query to use the getresultList( ) method to obtain a collection of results:
Parameters
2
EJB 3.0 QL Tutorial
www.sycorax.co.in
The : character followed by the parameter name is used in EJB QL statements to identify a
named parameter. The setParameter( ) method in this example takes the name of the
parameter first, and then the actual value. EJB QL also supports positional parameters. Let's
modify the previous example to see this mode in action:
Hints
Some Java Persistence vendors will provide additional add-on features that you can take
advantage of when executing a query. For instance, the JBoss EJB 3.0 implementation allows
you to define a timeout for the query. These types of add-on features can be specified as hints
using the setHint( ) method on the query. Here's an example of defining a JBoss query
timeout using hints:
FlushMode
Sometimes you would like a different flush mode to be enforced for the duration of a query. For
instance, maybe a query wants to make sure that the entity manager does not flush before the
query is executed (since the default value implies that the entity manager can). The Query
interface provides a setFlushMode( ) method for this particular purpose:
3
EJB 3.0 QL Tutorial
www.sycorax.co.in
Example:
@Entity
public class Customer {
private ind id;
private String first;
@Id
public int getId( ) { return id; }
public String getFirstName( ) { return first; }
public String getLastName( ) { return first; }
In this example, we are using get and set methods to define our persistent properties. The
SELECT clause would look like this:
When a query returns more than one item, you must use the Query.getResultList( ) method.
If the SELECT clause queries more than one column or entity, the results are aggregated in an
object array (Object[]) in the java.util.List returned by geTResultList( ). The following
code shows how to access the returned results:
Using DISTINCT
If a customer has more than one reservation, there will be duplicate references to that customer
in the result. Using the DISTINCT keyword ensures that each customer is represented only once
in the result:
4
EJB 3.0 QL Tutorial
www.sycorax.co.in
WHERE Clause
This is accomplished through the WHERE clause, which behaves in much the same way as the
WHERE clause in SQL.
For example, you can define an EJB QL statement that selects all the Customer entities that use a
specific brand of credit card. The literal in this case is a String literal. Literal strings are
enclosed by single quotes. Literal values that include a single quote, like the restaurant name
Wendy's, use two single quotes to escape the quote: Wendy''s. The following statement returns
customers that use Capital One credit cards. (If you don't want to bother with such details, use a
query parameter; the job will be done for you by the query API.)
SELECT c
FROM Customer AS c
WHERE c.creditCard.creditCompany.name = 'Capital One'
The LIKE comparison operator allows the query to select String type fields that match a
specified pattern. For example, the following EJB QL statement selects all the customers with
hyphenated names, like "Monson-Haefel" and "Berners-Lee":
This function returns the number of items in the query's final result set. The return type is a
java.lang.Long, depending on whether it is the return type of the query method. For example,
the following query provides a count of all the customers who live in Wisconsin:
SELECT COUNT( c )
FROM Customers AS c
WHERE c.address.state = 'WI'
5
EJB 3.0 QL Tutorial
www.sycorax.co.in
These functions can be used to find the largest or smallest value from a collection of any type of
field. They cannot be used with identifiers or paths that terminate in a relationship field. The
result type will be the type of field that is being evaluated. For example, the following query
returns the highest price paid for a reservation:
The MAX( ) and MIN( ) functions can be applied to any valid value, including primitive
types, strings, and even serializable objects.
The AVG( ) and SUM( ) functions can be applied only to path expressions that terminate in a
numeric primitive field (byte, long, float, etc.) or in one of their corresponding numeric
wrappers (Byte, Long, Float, etc.). The result of a query that uses the SUM( ) function has the
same type as the numeric type it's evaluating. The result type of the AVG( ) function is a
java.lang.Double, depending on whether it is used in the return type of the SELECT method.
For example, the following query uses the SUM( ) function to get the total amount paid by all
customers for a specific cruise (specified by the input parameter):
ORDER BY Clause
The ORDER BY clause allows you to specify the order of the entities in the collection returned by
a query. The semantics of the ORDER BY clause are basically the same as in SQL. For example,
we can construct a simple query that uses the ORDER BY clause to return an alphabetical list of all
of Titan Cruises' customers:
SELECT c
FROM Customers AS c
ORDER BY c.lastName
6
EJB 3.0 QL Tutorial
www.sycorax.co.in
The default order of an item listed in the ORDER BY clause is always ascending, which means
that the lesser values are listed first and the greater values last. You can explicitly specify
the order as ascending or descending by using the keywords ASC and DESC. The default is ASC.
The GROUP BY and HAVING clauses are commonly used to apply stricter organization to a query
and to narrow the results for aggregate functions. The GROUP BY clause is usually used in
combination with aggregate functions, because it allows you to cluster data by category.
The HAVING clause is used with a GROUP BY clause and acts as a filter, restricting the final output.
The HAVING clause employs aggregate functional expressions using only the identifiers used in
the SELECT clause. You can restrict the GROUP BY result by using the HAVING syntax.
Functional expressions
EJB QL has seven functional expressions that allow for simple String manipulation and three
functional expressions for basic numeric operations. The String functions are:
LOWER(String)
UPPER(String)
7
EJB 3.0 QL Tutorial
www.sycorax.co.in
Allows you to trim a specified character from the beginning (LEADING), end (trAILING),
or both (BOTH). If you do not specify a trim character, the space character will be
assumed.
CONCAT(String1, String2)
Returns the String that results from concatenating String1 and String2.
LENGTH(String)
Returns an int indicating the position at which String1 is found within String2. If it's
present, start indicates the character position in String2 at which the search should
start. Support for the start parameter is optional; some containers will support it, and
others will not. Don't use it if you want to ensure that the query is portable.
Returns the String consisting of length characters taken from String1, starting at the
position given by start.
ABS(number)
SQRT(double)
MOD(int, int)
Returns the remainder for the first parameter divided by the second (i.e., MOD(7, 5) is
equal to 2)
8
EJB 3.0 QL Tutorial
www.sycorax.co.in