Using Query Bind Parameters

Using query bind parameters in GemFire queries is similar to using prepared statements in SQL where parameters can be set during query execution. This allows user to build a query once and execute it multiple times by passing the query conditions during run time.

The use of query bind parameters is now supported in Client-to-Server queries.

The query parameters are identified by a dollar sign, $ , followed by a digit that represents the parameter's position in the parameter array passed to the execute method. Counting begins at 1, so $1 references the first bound attribute, $2 the second attribute, and so on.

The Query interface provides an overloaded execute method that accepts parameters inside an Object array. See the Query.execute JavaDocs for more details.

The 0th element of the Object array is used for the first query parameter, and so on. If the parameter count or parameter types do not match the query specification, the execute method throws an exception. Specifically, if you pass in the wrong number of parameters, the method call throws a QueryParameterCountInvalidException. If a parameter object type is not compatible with what is expected, the method call throws a TypeMismatchException.

In the following example, the first parameter, the integer 2, is bound to the first element in the object array. The second parameter, active, is bound to the second element.

Sample Code

// Identify your query string.
 String queryString = SELECT DISTINCT * FROM /exampleRegion p WHERE p.status = $1;

// Get QueryService from Cache.
QueryService queryService = cache.getQueryService();

// Create the Query Object.
Query query = queryService.newQuery(queryString);

// Set query parameters.
Object[] params = new Object[1];
params[0] = "active";

// Execute Query locally. Returns results set.
SelectResults results = (SelectResults)query.execute(params);

// Find the Size of the ResultSet.
 int size = results.size();
Additionally the query engine supports setting the region path as query parameter.
SELECT DISTINCT * FROM $1 p WHERE p.status = $2
To use a parameter in the FROM clause, the parameter reference must be bound to a collection. This query could be used on any collection by passing the collection in as a query parameter.