April 20, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Installing and Using the Torque Object Mapper, Page 3

  • September 5, 2002
  • By James M. Turner, James M. Turner
  • Send Email »
  • More Articles »

The getAllGames method demonstrates that one class in Torque can implement a query against another. In this case, the Pitcher's Id (which is of type NumberKey) is retrieved, and then placed as a condition on the Criteria. That Criteria then is used to look up matching rows in the GAME table. Basically, whatever Peer is used for the doSelect is the table that the query will be run against, and the type of object that will be returned. The getGamesAgainst method is the same as the getAllGames method, but with an additional condition checking for the opposing team.

The remainder of the code implements ERA computation, which is a relatively straightforward matter. With that in place, you can write your main class:

package pitchers;

import pitchers.torque.*;
import org.apache.torque.om.*;
import org.apache.torque.util.*;
import org.apache.torque.Torque;
import java.util.List;
import java.text.DecimalFormat;

public class PitcherStats {

  private static DecimalFormat df = new DecimalFormat("0.00");

  private static String[]
          teamnames = {"RedSox", "Yankees", "DevilRays",
                       "WhiteSox", "Cubs", "Dodgers", "Marlins",
                       "Angels", "Orioles", "Royals", "Athletics",
                       "BlueJays", "Tigers", "Rockies", "Braves"
                      };

  public static void main(String args[]) {
    if (args.length == 0) {
      System.out.println
             ("Usage: pitcher [add|init|game|era|eravs|clear]");
      return;
    }

    String command = args[0];

    try {
      Torque.init
             ("d:/gamelan/torque/bin/classes/Torque.properties");
      if (command.equals("init")) {
        for (int i = 0; i < teamnames.length; i++) {
          Team t = new Team();
          t.setTeamId(new NumberKey(i + 1));
          t.setTeamName(teamnames[i]);
          t.save();
        }
      }

      if (command.equals("clear")) {
        Criteria c = new Criteria();
        c.add(TeamPeer.TEAM_ID, -1, Criteria.GREATER_EQUAL);
        TeamPeer.doDelete(c);
      }

      if (command.equals("era")) {
        if (args.length != 3) {
          System.out.println("Usage: pitcher era last first");
          return;
        }
        Pitcher p = Pitcher.findPitcherByName(args[1], args[2]);
        if (p == null) {
          System.out.println("No such pitcher: " +
                              args[1] + " " + args[2]);
          return;
        }
        System.out.println("The ERA for " + args[1] + 
                            " " + args[2] + " is " + 
                            df.format(p.computeERA()));
      }

      if (command.equals("eravs")) {
        if (args.length != 4) {
          System.out.println
                 ("Usage: pitcher eravs last first team");
          return;
        }
        Pitcher p = Pitcher.findPitcherByName(args[1], args[2]);
        if (p == null) {
          System.out.println("No such pitcher: " +
                              args[1] + " " + args[2]);
          return;
        }
        Team t = Team.findTeamByName(args[3]);
        if (t == null) {
          System.out.println("No such team: " + args[3]);
          return;
        }
        System.out.println("The ERA for " + args[1] + 
                           " " + args[2] + " against the " +
                           args[3] + " is " +
                           df.format(p.computeERAAgainst(t)));
        }

        if (command.equals("add")) {
          if (args.length != 4) {
          System.out.println
                 ("Usage: pitcher add last first team");
          return;
        }

        Team t = Team.findTeamByName(args[3]);
          if (t == null) {
          System.out.println("No such team: " + args[3]);
          return;
        }
        Pitcher p = new Pitcher();
        p.setTeam(t);
        p.setFirstName(args[1]);
        p.setLastName(args[2]);
        p.save();
        System.out.println("Added player!");
        return;
      }
      if (command.equals("game")) {
        if (args.length != 9) {
          System.out.println
                 ("Usage: pitcher game first last team/opponent
                   hits runs outs walks Ks");
          return;
        }
        int divide = args[3].indexOf("/");
        if (divide == -1) {
          System.out.println("Format is pitcherteam/opposing");
          return;
        }
        String pitcherteam = args[3].substring(0, divide);
        String oppteam = args[3].substring(divide + 1);
        Pitcher p = Pitcher.findPitcherByName(args[1], args[2]);
        if (p == null) {
          System.out.println("No such pitcher: " +
                              args[1] + " " + args[2]);
          return;
        }

        Team team = Team.findTeamByName(pitcherteam);
        if (team == null) {
          System.out.println("No such team: " + pitcherteam);
          return;
        }

        Team opponent = Team.findTeamByName(oppteam);
        if (opponent == null) {
          System.out.println("No such team: " + oppteam);
          return;
        }

        int hits = Integer.parseInt(args[4]);
        int runs = Integer.parseInt(args[5]);
        int outs = Integer.parseInt(args[6]);
        int walks = Integer.parseInt(args[7]);
        int ks = Integer.parseInt(args[8]);

        Game i = new Game();
        i.setPitcher(p);
        i.setTeamRelatedByPlayingFor(team);
        i.setTeamRelatedByAgainstTeam(opponent);
        i.setHits(hits);
        i.setRuns(runs);
        i.setOutsRecorded(outs);
        i.setStrikeOuts(ks);
        i.setWalks(walks);
        i.save();
        System.out.println("Added Game!");
        return;
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
}

Most of this file is merely creating a command-line user interface for the business logic already implemented, but there are a few things to note. First, because this is a stand-alone application, it needs to call Torque.init explicitly, passing the location of the properties file. In a Web application, this could be handled by a servlet that's called during startup.

The "clear" function shows two features. First, if a Criteria condition is created with a third argument, that argument can be used to specify a test such as ">=" or "LIKE". In the case of the "clear" function, it is used to specify all records by specify all IDs > -1. It also shows the doDelete method on the Peer, which does what you'd expect, deleting all rows that match the Critieria.

The "game" function shows one last feature. If there is a one-to-one relationship between two tables by a foreign key, a get and set method are added to that table. For example, Game has a getPitcher and setPitcher method because Game joins to Pitcher by PITCHER_ID.

If one table has several one-to-one foreign-key relations to another table, Torque creates a special accessor. This takes the form of "getXRelatedByY, where X is the foreign table, and Y is the row of this table that is the key." It also works when creating rows. For example, the Game class has two foreign keys to Team, which can be accessed using getTeamRelatedByPlayingFor and getTeamRelatedByAgainstTeam (and the corresponding set methods.)

After compilation, you can take the code for a test drive:

D:\gamelan>.\pitcher add James Turner RedSox
Added player!

D:\gamelan>.\pitcher game James Turner
                     RedSox/Yankees 0 0 27 0 27
Added Game!

D:\gamelan>.\pitcher game James Turner RedSox/DevilRays 2 1 9 0 5
Added Game!

D:\gamelan>.\pitcher era James Turner
The ERA for James Turner is 0.75

D:\gamelan>.\pitcher eravs James Turner Yankees
The ERA for James Turner against the Yankees is 0.00

D:\gamelan>.\pitcher eravs James Turner DevilRays
The ERA for James Turner against the DevilRays is 3.00

D:\gamelan>.\pitcher era Derek Lowe
The ERA for Derek Lowe is 2.23

D:\gamelan>.\pitcher eravs Derek Lowe DevilRays
The ERA for Derek Lowe against the DevilRays is 1.16

The pitcher.bat file is just a wrapper on the Java call; that sets up the libraries correctly:

@echo off
set demodir=d:\gamelan
set classpath=%demodir%\torque\bin\classes;%demodir%\torque\lib\
    commons-collections.jar;%demodir%\torque\lib\
    commons-lang-0.1-dev.jar;%demodir%\torque\lib\
    jdbc2_0-stdext.jar;%demodir%\torque\lib\
    log4j-1.1.3.jar;%demodir%\torque\lib\
    stratum-1.0-b2-dev.jar;%demodir%\torque\lib\
    torque-3.0-b2.jar;%demodir%\torque\lib\
    velocity-1.3-dev.jar;%demodir%\torque\lib\
    village-1.5.3.jar;%demodir%\torque\lib\
    xercesImpl-2.0.0.jar;%demodir%\torque\lib\
    xmlParserAPIs-2.0.0.jar;%demodir%\torque\lib\
    mm.mysql-2.0.14-bin.jar;%demodir%\torque\lib\
    commons-configuration-1.0-dev.jar
java pitchers.PitcherStats %1 %2 %3 %4 %5 %6 %7 %8 %9

This tutorial just scratches the surface of what you can do with Torque, but is essentially all you need to know to develop a complete application using it. For more information or Torque, consult the Apache Web site at http://jakarta.apache.org/turbine/torque/index.html. You can find the complete sources to this application at http://www.blackbear.com/downloads/torque.jar.

James Turner is the owner and manager of Black Bear Software, LLC, which specializes in custom Java-based e-Commerce and CRM solutions delivery. He is also the author of "MySQL and JSP Web Applications: Data-Driven Programming Using Tomcat and MySQL" (ISBN: 0672323095) and is the co-author of "Struts: Kick Start" (ISBN: 0672324725), which will be published in November. He can be reached at turner@blackbear.com.





Page 3 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel