- Quick Intro to JDO
- The Problem at Hand
- Persisting the Objects
- Retrieving the Objects
- The Wrap-Up
Retrieving the Objects
To find our objects, we need to use JDOQL, JDO's query language; it's a bit like a clumsy mix of SQL and Java. JDOQL queries are run through a Query object, as shown in the persistQuoteSource method in Listing 4. What we want to do is pull all quotes from a specific QuoteSource that contain a certain bit of text. Unfortunately, JDOQL's ability to query based on string logic is rather limited, so we'll do this in two steps:
Ask the user which source of all the available sources to search, and pull all associated quotes into memory.
Use non-JDO methods to whittle down that list.
First, the code to pull all the applicable quotes from a QuoteSource (see Listing 6):
Listing 6 Retrieving all QuoteInfos for a particular QuoteSource
protected List getAllQuotesFromSource(QuoteSource source) throws Exception { Query query = null; List list = new ArrayList(); try { query = getPM().newQuery( QuoteInfo.class, "source == param"); query.declareParameters("QuoteSource param"); query.setOrdering("lineNumber ascending"); list.addAll((Collection)query.execute(source)); query.closeAll(); } catch(Exception e) { throw new Exception("Error querying for quotes by source: " + e); } return list; }
Next, the code to trim that list based on a string from user input (see Listing 7):
Listing 7 Filtering the list of QuoteInfos
protected List filterQuotes(List quotes, String test) { List returnList = new ArrayList(); QuoteInfo currQuoteInfo = null; for(int i = 0; i < quotes.size(); ++i) { currQuoteInfo = (QuoteInfo)quotes.get(i); if(currQuoteInfo.matches(test)) returnList.add(currQuoteInfo); } return returnList; }