A query is requested from the PersistenceManager. Therefore the PersistenceManager has a method newQuery(). Use this method to obtain a new instance of a javax.jdo.Query implementation.
Every query is run using the method execute() and should be closed using a close() call to release all acquired database resources.
The following source code demonstrates a query asking for all objects of a class - i.e. for all rows in a table:
PersistenceManager pm = ...
// create query for persons
Query query = pm.newQuery(Person.class);
// run query
Collection results = (Collection)query.execute();
// print persons last names
Iterator it = results.iterator();
while (it.hasNext())
{
Person p = (Person)it.next();
System.out.println(p.getLastName());
}
// close query
query.close(results);
When requesting a query, the class that is asked for should be passed to the persistence manager. This indicates (indirectly), which table is accessed in the data source.
Every query returns a Collection object as a result. This object represents the result set, which contains all objects you searched for. If no object could be found, an empty Collection is returned. You can use the Collection as you used to when dealing with other collections of objects (like ArrayList ). The example above uses an Iterator to read all elements from the Collection . Because every Collection only maintains elements of type Object , a cast is needed at every single access. After the cast you can use the object (a Person , for example) directly.
Make sure, that you close a query after use. Use the method close() on the query object and pass a reference to the result set that was returned by the query or simply use closeAll() .