Step 4: Example Queries
Here we show a number of jdoql queries to retrieve information from the relational store. For more information on JDOQL queries see here.
Note that in the examples below the implementation classes are being used.
Query to retrieve all books:
// reopen the pm/transaction pm = jpoxDataStore.getPersistenceManager(); tx = pm.currentTransaction(); tx.begin(); // retrieve all books Query qry = pm.newQuery("SELECT FROM " + BookImpl.class.getName()); Collection coll = (Collection)qry.execute(); System.out.println(((Book)coll.iterator().next()).getTitle()); // show a title System.out.println(((Book)coll.iterator().next()).getTitle()); // show a title
Query to retrieve all books which have a writer with the name of G. Orwell:
// retrieve a book which has a writer with the name of G. Orwell qry = pm.newQuery("SELECT FROM " + BookImpl.class.getName() + " WHERE " + " title==\"1984\" && author == writ && writ.name == \"G. Orwell\" " + "VARIABLES " + WriterImpl.class.getName() + " writ"); coll = (Collection)qry.execute(); System.out.println(coll.size()); // should be 1 Book bk = (Book)coll.iterator().next(); System.out.println(bk.getTitle()); // should be 1984 System.out.println(bk.getAuthor().getName()); // should be G. Orwell
Query to a retrieve a library with a name ending on Library:
// read the library with a name ending on Library qry = pm.newQuery("SELECT FROM " + LibraryImpl.class.getName() + " WHERE name.endsWith(\"Library\")"); coll = (Collection)qry.execute(); lib = (Library)coll.iterator().next();
Instead of using the implementation classes directly, it also possible to use the EMF generated interfaces and translate the interfaces to implementation classes. This hides the implementation classes. The JpoxHelper class offers a convenience method for this task.
qry = pm.newQuery("SELECT FROM " + BookImpl.class.getName() + " WHERE " + " title==\"1984\" && author == writ && writ.name == \"G. Orwell\" " + "VARIABLES " + WriterImpl.class.getName() + " writ"); System.err.println(((Collection)qry.execute()).size()); // retrieving all books qry = pm.newQuery("SELECT FROM " + BookImpl.class.getName()); System.err.println(((Collection)qry.execute()).size()); // retrieving all libraries with a name ending on library qry = pm.newQuery("SELECT FROM " + LibraryImpl.class.getName() + " WHERE name.endsWith(\"Library\")"); System.err.println(((Collection)qry.execute()).size()); // and really close of tx.commit(); pm.close();
The next step of this tutorial discusses the use of the EMF Resource concept.
Please click here to go to the next step.