Finding Objects

The method sampleQuery() shall demonstrate a database query. Therefore we use a query implementation javax.jdo.Query we can request from the persistence manager:

Query q = pm.newQuery(Person.class);
The class that is asked for should be passed as parameter to the query. You can pass more parameters to the query to define more search criteria (see chapter "Queries").

The query is run using the method execute() and should be closed using a close() call to release all acquired database resources. It is not essential to run a query inside a transaction.

Every query returns an object of the java.util.Collection interface as a result, that you can handle as usual. If no object can be found, the result is an empty Collection . Use an Iterator to navigate over the result set. You should close the query if you do not need the Collection anymore. Of course you should close the persistence manager too.

The following code demonstrates a query to search for all Person objects in a database:

public void sampleQuery() 
{
 PersistenceManager pm = pmf.getPersistenceManager();

 Query q = pm.newQuery(Person.class);
 Collection c = (Collection) q.execute();

 Iterator it = c.iterator();
 while (it.hasNext()){
  Person p = (Person) it.next();
  System.out.println("found " + p);
 }
 
 q.close(c);
 pm.close();
}