Cayenne User Documentation
Running Queries

Cayenne Query API is discussed in the following chapters. This chapter concentrates on how to execute an existing query via a DataContext. Still we'd like to point to a few aspects of the query API here, as they are important for the query execution discussion:

- There are selecting and non-selecting queries. Selecting queries return objects back to the caller, while non-selecting just perform some DB operation (such as INSERT, DELETE, UPDATE, etc.) without returning anything back.
- Queries can be created in two ways - either by instantiating and configuring a Query object directly, or by mapping a query in CayenneModeler, and then referring to it by name. Mapped named queries are generally easier to create and maintain.

Being an instance of QueryEngine, DataContext has generic API to execute any type of queries, however it is rarely used directly. Instead DataContext provides a number of overriden convenience methods to run the types of queries mentioned above.

### Running Query Instances

The following methods are used for running selecting and non-selecting Query objects built in the code:

- `public java.util.List performQuery(Query query)`
  This is the most commonly used method for any selecting query.

- `public ResultIterator performIteratedQuery(Query query) throws CayenneException`
  Performs a selecting query, returning an iterator over the result backed by an open JDBC ResultSet. Benefits and shortcomings of using result iterators are discussed in "Performance Tuning" chapter. This is the only query method that throws checked exceptions. Also returned ResultIterator requires explicit cleanup via calling close().

- `public int[] performNonSelectingQuery(Query query)`
  Executes a non-selecting query, returning update counts.

- `public QueryResponse performGenericQuery(Query query)`
  A generic query execution method. Used for queries with complex results. For example queries based on stored procedures can have more than one result set, do multiple updates, and return values as OUT parameters.

### Running Mapped Queries

The following methods are used to run named selecting and non-selecting queries mapped using CayenneModeler and stored in the DataMap XML file:

- `public java.util.List performQuery(String name, boolean expireCachedLists)`
  Runs a named selecting query stored in the DataMap.

- `public java.util.List performQuery(String name, Map parameters, boolean expireCachedLists)`
  Runs a named selecting query stored in the DataMap, using a map of named parameters.

- `public int[] performNonSelectingQuery(String name)`
  Runs a named non-selecting query stored in the DataMap.

- `public int[] performNonSelectingQuery(String name, Map parameters)`
  Runs a named non-selecting query stored in the DataMap, using a map of named parameters.

.
Copyright ©2001-2008 Apache Software Foundation