User's Manual

Chapter 9. Persistence Tutorial 75
To accomplish the task of retrieving the paragraphs as mentioned above, you could declare the fol-
lowing DataQuery in your PDL file:
model tutorial;
// the first line indicates that it is a query and the name of the query
query paragraphMagazines {
// the next section maps the attributes to the java type so that the
// same type is returned regardless of which database driver is used.
BigDecimal magazineID;
BigDecimal paragraphID;
String issueNumber;
String text;
do {
select m.magazine_id, p.paragraph_id, issue_number, text
from magazines m, a, magazine_article_map ma, paragraphs p
where ma.magazine_id = m.magazine_id
and p.article_id = ma.article_id
} map {
magazineID = m.magazine_id;
paragraphID = p.paragraph_id;
issueNumber = m.issue_number;
text = p.text;
}
}
With this PDL definition, it should be easy to see how the following code does what is desired (remove
the "\" and make it all one line).
DataQuery query = SessionManager.getSession().retrieveQuery\
("tutorial.paragraphMagazines");
query.addEqualsFilter("issueNumber", "5A");
while (query.next()) {
System.out.println((String)query.get("text"));
}
9.4.1.2. Creating Data Objects
The method discussed for retrieving arbitrary information from the database is sufficient to do most
of what is needed. However, it is not very convenient since most Java code is written around using
DataObjects. Therefore, most developers want to be able to retrieve DataObjects directly from
the DataQuery. One way to do this is to create a new DataObject for each row returned by the query
and then populate that DataObject with the information retrieved. While this works, it is inefficient
and inelegant.
To solve this problem, the DataQuery allows the developer to create DataObjects directly from
the query. The objects can be defined within the query statement in a fashion similar to Attribute
declarations.
Suppose you want to get all magazines that have authors of articles whose last name starts with a given
sequence of characters. This is not a standard association because you are actually going through
two separate mapping tables. This could be done by getting all articles with authors that match the
criteria and then getting all magazines that contain the articles. However, this option would require
two separate database hits. Another option is to perform a query and then for every row create the
corresponding data object. A third option is to have the persistence layer create the data objects for
you. The following example shows how you can allow the persistence layer to perform the work for
you.