Skip Headers

# Query-by-Example

Previous

Next

Query-by-example is a simple and intuitive way to express a query. To specify a query-by-example, provide a sample instance of the persistent object to query, and set appropriate values on only the data members on which you wish to query.

You can use a constructor with a reference class argument to create a sample instance or example object. Alternatively, you can use a combination of any other type of constructor and a `setReferenceClass` method of your query object. If you fail to specify the reference class, a `QueryException` will be thrown.

Query-by-example lets you query for an object based on any attribute that uses a direct mapping or a one-to-one relationship (including those with nesting).

Note: Query-by-example does not support any other relationship mapping types, nor does it support EJB beans.

Set only the attributes on which you base the query; set all other attributes to `null`. By default, TopLink ignores attributes in the sample instance that contain `null`, zero (0), empty strings, and `FALSE`. You can modify this list of values (and define other query by example options) by specifying a `QueryByExamplePolicy` (see "Defining a QueryByExamplePolicy").

Query-by-example uses the `AND` operator to tie the attribute comparisons together. By default, attribute values in the sample instance are compared against corresponding values of candidate objects using `EQUALS` operator. You can modify this behaviour using the `QueryByExamplePolicy`.

Both `ReadAllQuery` and `ReadObjectQuery` provide a `setExampleObject` method and `setQueryByExamplePolicy` method that you can use to specify selection criteria based on an example object instance.

For more information and examples, see "Reading Objects Using Query-By-Example".