Sie sind auf Seite 1von 2

EJBQL 3.

0 Quick Reference Guide Parameters Optimizations


Parameters can be specified in query strings by placing a Limiting/paging query results:
colon in front of the identifier. (i.e. :param) Return a subset of the results, here, items 10 through 30.
Query q = em.createQuery(...);
Simple parameters: q.setMaxResults(20);
Find all people named “John”. Parameters allow using q.setFirstResult(10);
known data in the query, in this case a String.
Query q = em.createQuery(“select p from “ Flush mode:
+ “Person p where p.firstName=:param”); Set flushes to occur at commit or before query execution. If
q.setParameter(“param”, “John”); the flush mode is set to FlushModeType.COMMIT, changes
List<Person> people = (List<Person>) made during the transaction might not be visible in the
q.getResultList(); query execution results.
Query Structure query.setFlushMode(FlushModeType.AUTO);
Query clauses must be in the specified order. Bulk Update and Delete query.setFlushMode(FlushModeType.COMMIT);
select [distinct] [new] <result> Performed for a single type of entity per statement.
from <identification-variable> Single Result
[[left | inner] join [fetch] <objects to join> ] Update: Specify that only one result is expected and to return only
[where <filter>] Replace nickname Johnny with name John. the single instance instead of a List.
[group by <grouping-clause> ] Query q = em.createQuery(“update Person p “ Query q = em.createQuery(“select distinct p”
[having <filter>] + “set p.firstName = ‘John’ where “ + “ from Person p where p.firstName = “
+ “p.firstName = ‘Johnny’”); + “'UniqueName'“);
[order by <ordering-clause>]
int numUpdates = q.executeUpdate(); Person john = (Person) q.getSingleResult();
update < identification-variable >
Delete: Aggregates, Projections, and Grouping
set < identification-variable.field = new_value >
Delete all those with no children. Delete does not cascade Grouping allows aggregates and projections to be grouped
[where <filter>] Query q = em.createQuery(“delete from “ by a given field and optionally limited using “having”.
+ “Person p where p.children is empty”); Available aggregates are min, max, sum, avg, and count.
delete from < identification-variable > int numDeleted = q.executeUpdate();
[where <filter>]
Simple grouping:
Query Examples Subqueries select avg(p.age) from Person p
The following examples use this sample class and Find the youngest people in the company. group by p.firstName
assume an EntityManager named “em”. select p from Person p where p.age =
@Entity(access=AccessType.FIELD) (select min(p.age) from Person p) Limiting grouping with “having” expression:
public class Person {
@Id private int id; Group by firstName where the firstName starts with “J”.
Find those whose last name is part of a street address. select count(p) from Person p
@Version private long version; select p from Person p where p.lastName in group by p.firstName
private int age; (select a.street from Address a) having lower(p.firstName) like ‘j%’
private String firstName;
private String lastName;
@OneToOne private Address address; Ordering Results EJBQL from JDO
@OneToMany private Set<Person> children; Order query results by age, oldest first. Execute an EJBQL query via the JDO Query interface.
} select p from Person p order by p.age desc Query q = pm.newQuery(
Basic Example kodo.query.QueryLanguages.LANG_EJBQL,
Query q = em.createQuery(“select p from “ Order query results by name, from A to Z, and then by “select p from Person p where ”
+ “Person p where p.firstName=’John’”); age, from oldest to youngest. + “p.address.state = :stateCode”);
List<Person> people = (List<Person>) select p from Person p List<Person> people = (List<Person>)
q.getResultList(); order by p.firstName asc, p.age desc q.execute(“MA”);
for (Person person : people)
log(person.getLastName());

© 2005 SolarMetric, Inc.


Content based upon EJB3.0 public draft http://solarmetric.com/resources/ejbql-quickref.pdf
EJBQL 3.0 Quick Reference Guide Where Clause Methods Result Classes and Aliases
The following methods may be used as part of a query You can have query results placed directly into a custom
where clause. For example, “where p.firstName like class. This example uses the custom class Name below.
(‘%ohn%’)” or “where sqrt(p.age) > 6”. public class Name
General is [not] null, {
[not] exists private String first;
Collection size(Collection) private String last;
member [of], public Name(String f, String l) {
[not] in this.first = f;
is [not] empty, this.last = l;
all | any | some }
String [not] like, // ...
concat(String, String), }
SQL Queries
trim([leading | trailing |
Queries can use direct SQL. both] <char to trim> Query q = em.createQuery(“select “
Find people whose first name is “John”. [from] String) + “new com.example.Name(p.firstName, “
Query sql = em.createNativeQuery(“SELECT” lower(String), + “p.lastName) from Person p “
+ “ FIRST, LAST, AGE FROM PERSON” upper(String), + “where p.age > :param”);
+ “ WHERE FIRST = ‘JOHN’”, length(String), List<Name> names = (List<Name>)
com.example.Person.class); locate(String, String[, int q.setParameter(“param”, 30).
List<Person> people = (List<Person>) startpoint]), getResultList();
sql.execute(); substring(int, int) for(Name name : names)
abs(numeric), printLabel(name);
Math
Named Queries sqrt(numeric),
mod(numeric, numeric) Joins
Query definition: Date [not] between
@NamedQuery(name=“minorsByFirstName”, Inner join:
queryString=“select p from Person p Regular Expressions Select all people named John that have children.
where p.age < 18 group by The “like” expression accepts limited wildcard matching. select p from Person p join p.children c
p.firstName”) where p.firstName = ‘John’
_ represents a single character
Use of the keyword ‘inner’ is optional
% represents multiple characters
Use the named query in code:
List<Person> minors = (List<Person>) All people with ‘rick’ in their name – Patrick, Rick, etc.
select p from Person p The prior query is equivalent to this EJB 2.1 query.
em.createNamedQuery( select object(p) from Person p,
where lower(p.firstName) like ‘%rick%’
“minorsByFirstName”).getResultList(); in(p.children) c where p.firstName=‘John’
Where Clause Operators
Keywords = equal (note: can be used with Strings)
Left outer join:
Reserved keywords are not case sensitive. <> not equal
Select the last name of every person and the age of each of
> greater than
his/her children, if any.
select, from, where, update, delete, < less than select p.lastName, c.age from Person p
join, outer, inner, group, by, having, >= greater than or equal left join p.children c
fetch, distinct, object, null, true, <= less than or equal
false, not, and, or, between, like, in, AND conditional AND Fetch join:
as, unknown, empty, member, of, is, avg, OR conditional OR
max, min, sum, count, order, by, asc, Select everyone named John and eagerly fetch information
- subtract or convert sign about any children.
desc, mod, upper, lower, trim, position,
character_length, char_length, + add select distinct p from Person p
bit_length, current_time, current_date, * multiply left join fetch p.children
current_timestamp, new, left, exists, / divide where p.firstName=‘John’
all, any, some, size NOT logical complement

© 2005 SolarMetric, Inc.


Content based upon EJB3.0 public draft http://solarmetric.com/resources/ejbql-quickref.pdf

Das könnte Ihnen auch gefallen