Step 5: Writing a Sample Application

Congratulations, you have finally reached the fun the part of this tutorial. This is where you'll discover the power of Torque.

As mentioned earlier, when Torque created your object model, it created eight Java classes for each table defined in your database schema. For example, the book table, defined in the database schema presented earlier, will result in the following classes: Book, BookPeer, BookPeerImpl, BookRecordMapper, BaseBook, BaseBookPeer, BaseBookPeerImpl, and BaseBookRecordMapper.

Book, BookPeer, BookPeerImpl and BookRecordMapper are subclasses of BaseBook, BaseBookPeer BaseBookPeerImpl and BaseBookRecordMapper, respectively. BookPeer and BaseBookPeer are simply static wrappers of BookPeerImpl and BaseBookPeerImpl. The four Base classes (Base*) contain Torque-generated logic and should not be modified because Torque will overwrite your changes if you happen to generate your object model again. Any business logic that you might want to add should be placed in the Book and either BookPeerImpl or BookPeer classes (this is covered later in the tutorial).

You might be asking yourself, what is the difference between the BookPeer, BookPeerImpl, BookRecordMapper and Book classes? The BookPeer and BookPeerImpl classes provide the same functionality, with the difference that the Peer classes provide static access to methods for manipulating tables while the PeerImpl classes contain the implementation of those methods. This allows the implementation to be exchanged after compilation (e.g. for testing purposes). If you do not need to exchange the implementation of the Peer classes, you need not bother about the PeerImpl classes and simply use the Peer classes. The Book class (also known as "Data Object" class), "wrap" individual rows within the tables and provide getters/mutators for each column defined in those tables as well as a save method. The RecordMapper classes map between JDBC Rows and the Data objects (chances are that you never use these directly). So the two of the eight classes you will probably be working with are the Peer classes (wrapping the table) and Data Objects (wrapping a table row) These have a one-to-one mapping to a table defined in your database schema. For a more in-depth discussion on Peers and Data Objects, refer to the Runtime relevant classes documentation. An example of adding logic to both the Peer and Data Objects is presented later in the tutorial.

Now that we've covered the basics of the object model that Torque generated for you, the rest of this section describes the Torque way of doing database inserts, selects, updates, and deletes illustrated with small segments of code. These segments of code are part of a sample application that is presented in full after a brief discussion on extending the object model classes. Finally, instructions on how to compile and run the application are detailed.

Inserting Rows

Inserting rows into your tables is easy with Torque. Simply instantiate a new Data Object of the appropriate class, set its properties using the mutators named after the table's columns, then invoke the Data Object's save method. Note: It is not necessary to set the object's primary key ID because Torque will do this for you automatically unless you've specified otherwise (see the Database Schema Configuration section above).

For example, to insert a new row in the author table (as defined in this tutorial's database schema): instantiate a new Author object, invoke the object's setFirstName and setLastName methods with appropriate values, then call the save method. That's it. The following is from the sample application:

Publisher addison = new Publisher();
addison.setName("Addison Wesley Professional");
addison.save();

Author bloch = new Author();
bloch.setFirstName("Joshua");
bloch.setLastName("Bloch");
bloch.save();

Inserting a row in a table that contains a foreign key is also simple. As a convenience, Torque creates a mutator for the specific Data Object class that represents the foreign-key in the object model. The name of this method is setTable where Table is the name of the foreign-key's table (as defined in the database schema). Upon calling this method with a reference to the appropriate Data Object, Torque will automatically extract and insert the foreign-key for you.

For example, the book table (as defined in the database schema) contains two foreign-keys: author_id and publisher_id. To insert a row in this table, follow the same procedure as above, but instead of explicitly setting the foreign-keys (via setAuthorId and setPublisherId), use setAuthor and setPublisher and pass references to an Author and Publisher Data Object. Both methods are illustrated in the following code which builds upon the earlier objects that were created:

/*
 * Using the convenience methods to handle
 * the foreign keys.
 */
Book effective = new Book();
effective.setTitle("Effective Java");
effective.setISBN("0-618-12902-2");
effective.setPublisher(addison);
effective.setAuthor(bloch);
effective.save();

/*
 * Inserting the foreign-keys manually.
 */
Book tcpip = new Book();
tcpip.setTitle("TCP/IP Illustrated, Volume 1");
tcpip.setISBN("0-201-63346-9");
tcpip.setPublisherId(addison.getPublisherId());
tcpip.setAuthorId(stevens.getAuthorId());
tcpip.save();

As you can see, inserting rows into your database is very easy to do with your Torque object model.

Selecting Rows

Selecting rows from your database is just as easy as inserting rows. The Peer class associated with a table defines a static method called doSelect which is used to pull data out of the table. The argument to doSelect is a Criteria object. It is this object that specifies the criteria to be used when selecting data from the database. As a result of the query, doSelect returns a List of Data Objects representing the rows of data selected.

For example, to select all of the rows from the book table that were inserted in the previous section, you must first create a Criteria object. Because we want to select everything from the table, no criteria will be specified (i.e. no WHERE clause in the underlying SELECT statement). To perform the query, the empty Criteria object is passed to BookPeer.doSelect, as illustrated below:

Criteria crit = new Criteria();
List<Book> books = BookPeer.doSelect(crit);

The results are stored in a List which can then be iterated over to access the individual Book objects retrieved from the table. The following code prints the Book to standard output (a better approach is presented later):

for (Book book : books)
{
    System.out.println("Title: " + book.getTitle() + "\n");
    System.out.println("ISBN:  " + book.getISBN() + "\n");
    System.out.println("Publisher: " +
            book.getPublisher().getName() + "\n");
    System.out.println("Author: " +
            book.getAuthor().getLastName() + ", " +
            book.getAuthor().getFirstName() + "\n");
}

In the above example, you may have noticed that by calling getAuthor and getPublisher, the object model automatically retrieved the Author and Publisher Data Objects for you. This results in an additional behind-the-scenes SQL query for each table. Although getAuthor is called twice, only a single SQL query occurs because all of the Author columns are selected in behind-the-scenes query.

The Gory Details (not for the faint)
Even still, this is not the most efficient method to query and populate Data Objects for an entire table with foreign-keys (one query for the table, then two additional queries for each row). Two single queries for selecting all associated authors respectively publishers would be much more efficient. As a convenience, Torque can generate filler methods which do exactly this: pass in a list of books retrieve all associated books resp. publishers and fill the cached authors resp. publishers in the book objects. For generating these methods, you need to set the switch torque.om.complexObjectModel.generateFillers to true when generating the classes.
As an alternative, for selects using joins, there are the doSelectJoin${table} methods in the BasePeer classes whose tables contain foreign-keys, where ${table} is the name of the foreign-key table. This method efficiently queries the database (using a single join query) and automatically populates all of the Data Objects. This eliminates the additional query that is issued when retrieving the foreign-key Data Object. For example, doSelectJoinAuthor and doSelectJoinPublisher were generated in the BaseBookPeer class that BookPeer extends. Torque does not generate a doSelectJoinAll or doSelectJoinAuthorPublisher method, because these methods would be inefficient for a large number of associated objects (n authors and m publishers per book would result in n*m rows per book, where n+m rows should suffice. Imagine n=100 and m=100...)

To select a specific Book from the table, create a Criteria object (or just reuse the previous one) and use the where methods to specify a condition. Specifying a condition is simply a matter of choosing a column (defined as static constants in your Peer class) and some value you want to match. Thus, selecting a book with the following ISBN, 0-618-12902-2, is as simple as:

Criteria crit = new Criteria();
crit.where(BookPeer.ISBN, "0-618-12902-2");
List<Book> books = BookPeer.doSelect(crit);

This section has only skimmed the surface of Criteria objects. Criteria can be used to specify very simple to very complex queries. For a much more in-depth discussion of Criteria, please refer to the Reading from the Database Reference.

Updating Rows

Updating a row in a table is only a matter of changing one or more properties of the Data Object that represents the row by invoking one or more mutators and then calling its save method. When a mutator is called, the Data Object sets an internal flag to indicate that its been modified. This flag is checked when save is invoked to determine if the Peer's doInsert or doUpdate is called to perform the database operation.

For example, changing the author of the Effective Java book created earlier is as simple as:

effective.setAuthor(stevens);
effective.save();

Deleting Rows

Deleting rows from a table is easy as well. The Peer class defines a static method doDelete which can be used for this purpose. Similar to the other Peer methods, doDelete may be passed a Criteria object or a Data Object to specify which row or rows to delete. It should be noted that there is no corresponding method in the Data Object to delete a row.

For example, the following code deletes all of the rows from the three tables that were inserted during the course of this tutorial using both forms of doDelete. First, the books are deleted by specifying Criteria, then the authors and publishers are deleted by passing the Data Objects directly to doDelete.

crit = new Criteria();
crit.add(BookPeer.ISBN, "0-618-12902-2");
BookPeer.doDelete(crit);

crit = new Criteria();
crit.add(BookPeer.ISBN, "0-201-63346-9");
crit.add(BookPeer.TITLE, "TCP/IP Illustrated, Volume 1");
BookPeer.doDelete(crit);

AuthorPeer.doDelete(bloch);
AuthorPeer.doDelete(stevens);
PublisherPeer.doDelete(addison);

Note: Deleting a row from a table that contains foreign-keys does not automatically delete the foreign-keys from their tables. If you want to delete the foreign-keys, you must do so explicitly as shown in the above example. I.e., deleting the books from the book table does not automatically delete the corresponding rows in the author and publisher tables.

Adding Functionality to the Object Model

This section will provide examples of adding functionality to both the Peer and Data Object classes. As you may recall, Torque generated eight classes for each table defined in the database schema. Four of these classes (the Base classes) contain Torque-generated logic while the other ones are empty subclasses that you can use to include business logic. By now, you should have a decent understanding of the type of logic that might be added to these classes. Keep in mind, Torque will overwrite any changes that are inadvertently added to the Base classes if you regenerate your object model; however, it will not overwrite changes in the non-Base classes.

The first change that we'll make to our object model is to provide our Data Objects with adequate toString methods. Theses methods can then be used to print the Data Objects without adding unnecessary code to the core of the application. The following are the modified Book, Author, and Publisher classes (located under the src/main/generated-java/org/apache/torque/tutorial/om directory):

// Book.java
package org.apache.torque.tutorial.om;

import org.apache.torque.TorqueException;

public class Book extends BaseBook
{
    public String toString()
    {
        StringBuffer sb = new StringBuffer();
        try
        {
            sb.append("Title:     " + getTitle() + "\n");
            sb.append("ISBN:      " + getISBN() + "\n");
            sb.append("Publisher: " + getPublisher() + "\n");
            sb.append("Author:    " + getAuthor() + "\n");
        }
        catch (TorqueException ignored)
        {
        }
        return sb.toString();
    }
}

// Author.java
package org.apache.torque.tutorial.om;

public class Author extends BaseAuthor
{
    public String toString()
    {
        return getLastName() + ", " + getFirstName();
    }
}

// Publisher.java
package org.apache.torque.tutorial.om;

public class Publisher extends BasePublisher
{
    public String toString()
    {
      return getName();
    }
}

The next change that we'll make is to the Peer classes. For convenience (and based on the suggestion in the Reading from the Database Reference) we'll add doSelectAll methods which will return a List of all the Data Objects in a table. The following are the modified BookPeer, AuthorPeer, and PublisherPeer classes which are located in the same directory as the Data Objects:

// BookPeer.java
package org.apache.torque.tutorial.om;

import java.util.List;
import org.apache.torque.TorqueException;
import org.apache.torque.criteria.Criteria;

public class BookPeer extends BaseBookPeer
{
    public static List<Book> doSelectAll() throws TorqueException
    {
        Criteria crit = new Criteria();
        return doSelect(crit);
    }
}

// AuthorPeer.java
package org.apache.torque.tutorial.om;

import java.util.List;
import org.apache.torque.TorqueException;
import org.apache.torque.criteria.Criteria;

public class AuthorPeer extends BaseAuthorPeer
{
    public static List<Author> doSelectAll() throws TorqueException
    {
        Criteria crit = new Criteria();
        return doSelect(crit);
    }
}

// PublisherPeer.java
package org.apache.torque.tutorial.om;

import java.util.List;
import org.apache.torque.TorqueException;
import org.apache.torque.criteria.Criteria;

public class PublisherPeer extends BasePublisherPeer
{
    public static List<Publisher> doSelectAll() throws TorqueException
    {
        Criteria crit = new Criteria();
        return doSelect(crit);
    }
}

In order to execute the full application presented at the end of this tutorial, you must make the above changes to your object model. After you have made the changes, proceed to the next section.

Full Application

The following is the sample bookstore application in its entirety. It should look very familiar if you've been following this tutorial. In fact, its almost identical with the exception that it utilizes the new functionality that was added to the object model in the previous section. Note in particular the all-important initialization of Torque using the torque.properties file we created earlier.

Create a file src/main/java/org/apache/torque/tutorial/om/Bookstore.java with the following content

package org.apache.torque.tutorial.om;

import java.io.InputStream;
import java.util.List;

import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.torque.Torque;
import org.apache.torque.criteria.Criteria;

public class Bookstore
{
    public static void main(String[] args)
    {
        try
        {
            // Initializing Logging
            BasicConfigurator.configure();
            Logger.getRootLogger().setLevel(Level.WARN);

            // Initializing Torque
            InputStream torqueConfigStream 
                    = Bookstore.class.getResourceAsStream("/torque.properties");
            PropertiesConfiguration torqueConfiguration 
                    = new PropertiesConfiguration();
            torqueConfiguration.load(torqueConfigStream);
            Torque.init(torqueConfiguration);

            /*
             * Creating new objects. These will be inserted into your database
             * automatically when the save method is called.
             */
            Publisher addison = new Publisher();
            addison.setName("Addison Wesley Professional");
            addison.save();

            Author bloch = new Author();
            bloch.setFirstName("Joshua");
            bloch.setLastName("Bloch");
            bloch.save();

            /*
             * An alternative method to inserting rows in your database.
             */
            Author stevens = new Author();
            stevens.setFirstName("W.");
            stevens.setLastName("Stevens");
            AuthorPeer.doInsert(stevens);

            /*
             * Using the convenience methods to handle the foreign keys.
             */
            Book effective = new Book();
            effective.setTitle("Effective Java");
            effective.setISBN("0-618-12902-2");
            effective.setPublisher(addison);
            effective.setAuthor(bloch);
            effective.save();

            /*
             * Inserting the foreign-keys manually.
             */
            Book tcpip = new Book();
            tcpip.setTitle("TCP/IP Illustrated, Volume 1");
            tcpip.setISBN("0-201-63346-9");
            tcpip.setPublisherId(addison.getPublisherId());
            tcpip.setAuthorId(stevens.getAuthorId());
            tcpip.save();

            /*
             * Selecting all books from the database and printing the results to
             * stdout using our helper method defined in BookPeer (doSelectAll).
             */
            System.out.println("Full booklist:\n");
            List<Book> booklist = BookPeer.doSelectAll();
            printBooklist(booklist);

            /*
             * Selecting specific objects. Just search for objects that match
             * this criteria (and print to stdout).
             */
            System.out.println("Booklist (specific ISBN):\n");
            Criteria crit = new Criteria();
            crit.where(BookPeer.ISBN, "0-201-63346-9");
            booklist = BookPeer.doSelect(crit);
            printBooklist(booklist);

            /*
             * Updating data. These lines will swap the authors of the two
             * books. The booklist is printed to stdout to verify the results.
             */
            effective.setAuthor(stevens);
            effective.save();

            tcpip.setAuthor(bloch);
            BookPeer.doUpdate(tcpip);

            System.out.println("Booklist (authors swapped):\n");
            booklist = BookPeer.doSelectAll();
            printBooklist(booklist);

            /*
             * Deleting data. These lines will delete the data that matches the
             * specified criteria.
             */
            crit = new Criteria();
            crit.where(BookPeer.ISBN, "0-618-12902-2");
            BookPeer.doDelete(crit);

            crit = new Criteria();
            crit.where(BookPeer.ISBN, "0-201-63346-9");
            crit.and(BookPeer.TITLE, "TCP/IP Illustrated, Volume 1");
            BookPeer.doDelete(crit);

            /*
             * Deleting data by passing Data Objects instead of specifying
             * criteria.
             */
            AuthorPeer.doDelete(bloch);
            AuthorPeer.doDelete(stevens);
            PublisherPeer.doDelete(addison);

            System.out.println("Booklist (should be empty):\n");
            booklist = BookPeer.doSelectAll();
            printBooklist(booklist);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /*
     * Helper method to print a booklist to standard out.
     */
    private static void printBooklist(List<Book> booklist)
    {
        for (Book book : booklist)
        {
            System.out.println(book);
        }
    }
}
  

Where to next

Now you have finished writing your sample application. The next step shows you how to compile and run the sample application.

Next we will look at Compiling and Running the Sample Application. Maven users please look here, and ant users please look here

User Comments

User comments for this step