About this Tutorial

このチュートリアルについて

This tutorial is intended to give first-time users an introduction to using Torque, an object-relational tool. Torque was developed as part of the Turbine web application framework. Until recently, it was tightly coupled in that framework, and could not be used independently. This tutorial is an introduction to the decoupled version of Torque.

このチュートリアルは、オブジェクト・リレーショナルツールであるTorqueを使うことを始めのユーザに紹介することを意識して書かれたものです。 TorqueはWEBアプリケーションフレームワークであるTurbineの一部として開発されました。 Torqueは最近までTurbineと強く結びついており、独立して使用することができませんでした。 このチュートリアルはTorqueがTurbineから独立したバージョンを紹介しています。

This will include how to obtain the Torque distribution, setting up a database, and writing a sample application to demonstrate the power of Torque. The tutorial is not meant to be an exhaustive introduction to Torque, please refer to the documentation on the Torque homepage for more detailed information.

このチュートリアルはTorqueの威力のデモンストレーションのため、 Torqueディストリビューションの取得、データベースのセットアップ、 サンプルアプリケーションの記述方法を含んでいます。 このチュートリアルはTorqueの紹介を網羅する意図で書かれていませんので、 詳しい情報はTorqueのホームページのドキュメントを参照して下さい。

The example used throughout this tutorial is based on an email sent to the turbine-user mailing list by Steven F. Davis called torque outside turbine - detailed example (long).

このチュートリアルを通して使われている例は、 Steven F. Davisによってturbine-userのメーリングリストに投稿されたTurbineの外部でのTorque(torque outside turbine)という詳細な例(長文)に基づいています。

Step 1: Obtaining the Torque Distribution

Step 1: Torqueのディストリビューションの取得

First, you need to obtain the Torque distribution. As of this writing, the standalone version of Torque has not been released; however, there is a beta version available.

まず最初に、Torqueディストリビューションの取得が必要です。 これを書いている時点では、Torqueの独立したバージョンはリリースされていませが、 ベータ版は入手可能です。

After you have obtained your copy of the Torque, you can either unpack the jar and integrate all of the Torque files into your source tree, or keep Torque in the jar and use it via the classpath.

Torqueコピーの取得をした後、jarを展開して、 すべてのTorqueファイルをソースツリー下に統合するか、 もしくはTorqueをjarのままにしておき、クラスパスを通すことでjarを使用します。

This tutorial will take the former approach. See jar guide for a description of the latter approach.

このチュートリアルでは前者の方法をとります。 後者の方法が書いてあるjarガイドも参照して下さい。

You need to unpack the Torque jar to a directory where you want to develop your application. This will create a directory called torque. It is here that you will configure Torque and build your application.

Torqueのjarを、開発しようとしているアプリケーションのディレクトリに展開する必要があります。 これで作られるディレクトリをtorqueと呼びます。 ここがTorqueを設定し、アプリケーションをビルドするディレクトリです。

Step 2: Configuring Torque

Step 2: Torqueの設定

The following section outlines the necessary steps to define your database schema and configure Torque to use your schema. Upon completion, you'll be able to use Torque to create your object model and all of the Java classes that support it. In addition, Torque can generate and execute all of the appropriate SQL commands to create your database, freeing you from doing it yourself.

このセクションではデータベーススキーマの定義と、 そのスキーマを使うTorqueを設定するために必要なステップの概要を述べます。 これが完了すれば、オブジェクトモデルとそれを扱うJavaクラスをすべて生成するために、 Torqueを使うことができるようになります。 それに加えて、Torqueはデータベースを作成するための適切なSQLコマンドを作成・実行してくれるので、 それを自分で行わなくても済むようになります。

To accomplish all of the above, you only need to create/edit three files: the Torque build properties, the Torque database schema, and the Torque run-time properties. Each of these files is covered in the following sections.

上記のことをすべて成し遂げるために必要なことは、 3つのファイルを作成/編集することだけです。 そのファイルとは、Torqueビルドプロパティ、Torqueデータベーススキーマ、 そしてTorqueランタイムプロパティです。 以下に、それぞれのファイルについて説明します。

Torque Build Properties

Torqueビルドプロパティ

Torque is a system that literally builds Java source/class files representing your object model, SQL statements for your specific database, and documentation. To accomplish these tasks, it uses Ant to control its build process, and ant uses the build.properties file in the top-level Torque directory to setup your development environment. It is this file that we will now edit.

Torqueはオブジェクトモデルを表現するJavaソース/クラス、 アプリケーション特有のデータベースのためのSQL構文、 そしてドキュメントを正確に組み立てるシステムです。 これらの処理を実現するため、Torqueはビルドの処理をコントロールするAntを使用します。 そしてAntは開発環境をセットアップするためにTorqueディレクトリ直下にあるbuild.propertiesファイルを使用します。 それがこれから編集するファイルです。

Keep in mind, this tutorial is going to show you the bare minimum to get your first Torque application up and running. However, the build.properties file is thoroughly commented, so please refer to it if you have a question regarding part of the file that is not covered here. Make the following changes and edit appropriately for your environment. The properties are described in the table following (note: you'll need to add the torque.database.buildUrl property):

このチュートリアルは、はじめてのTorqueアプリケーションをセットアップし、 動かすための最小のことがらを示そうとするものだということを忘れないで下さい。 しかし、build.propertieファイルの法には徹底的にコメントが書かれていますので、 ここで説明されていない部分について疑問があればここを参照して下さい。 次の部分を変更し、環境にあわせて適切に編集して下さい。 各プロパティに関して、次のテーブルに記述します。 (注:torque.database.buildUrl プロパティを追加する必要があります。)

  torque.project = bookstore
  torque.database = mysql
  torque.targetPackage = com.kazmier.om
  torque.database.createUrl = jdbc:mysql://127.0.0.1/mysql
  torque.database.buildUrl = jdbc:mysql://127.0.0.1/bookstore
  torque.database.url = jdbc:mysql://127.0.0.1/bookstore
  torque.database.driver = org.gjt.mm.mysql.Driver
  torque.database.user = adminuser
  torque.database.password = adminpassword
  torque.database.host = 127.0.0.1

For a reference as to what each property, and others, controls, please see the properties reference.

各プロパティ、その他、コントロールに関して照会するには プロパティリファレンスを参照して下さい。

Setting these properties correctly is very important. These enable Torque to generate all of the required sources and SQL for your specific database. If you experience problems later in this tutorial, it would be wise to double-check these values.

これらのプロパティを正確に設定することがとても重要です。 これらのプロパティはTorqueに対して、 アプリケーション特有のデータベースに必要なソースやSQLを生成できるようにします。 もし、後でこのチュートリアルで問題が起きたら、 これらの値を再確認することが賢明です。

Torque Database Schema

Torqueデータベーススキーマ

The second file that you must edit to configure Torque is the database schema. The database schema is an XML file that represents your SQL database in Torque. This is where you define all of your tables, column names and types, as well as the keys used to index these tables.

Torqueを設定するために編集しなければならない2つ目のファイルは、 データベーススキーマです。 このファイルはTorque内でSQLデータベースを表すXMLファイルです。 ここで、テーブル、カラム名およびデータ型のすべてを定義し、同様に、 これらのテーブルにインデックスを付けるために使用されるキーも定義します。

The database schema file is located in the torque/schema directory. Here you will find two XML files: id-table-schema.xml and project-schema.xml. The id-table-schema.xml file is used internally by Torque's IDBroker service (which is a database independent method for generating unique IDs). project-schema.xml is where you'll define your database schema. Historically, the name of your database schema file was required to be in the format of name-schema.xml where name was the same as the project property defined in build.properties; otherwise, Torque was not be able to find your database schema file. This is no longer the case, name is no longer restricted to the project name. However, it must end with ‘-schema.xml’ because Torque will only generate object models for files ending with that pattern.

データベーススキーマファイルは、torque/schemaディレクトリにあります。 そこにはid-table-schema.xmlproject-schema.xmlの2つのXMLがあります。 id-table-schema.xmlファイルは、 TorqueのIDBrokerサービスによって内部で使用されます。 (このサービスはユニークなIDを生成する、データベースに依存しないメソッドです。) project-schema.xmlは、データベーススキーマを定義する場所です。 データベーススキーマファイルのファイル名は歴史的に、 name-schema.xmlのようなフォーマットであり、 name部分がbuild.propertiesに定義されているprojectプロバティと同じ値を持つことが要求されていました。 そうしなければ、Torqueはあなたのデータベーススキーマファイルを見つけることができませんでした。 もはやこのような問題はなく、name部分がプロジェクト名に制限されてはいません。 しかしながら、Torqueは‘-schema.xml’で終わるファイルに対してのみ、オブジェクトモデルを作成するので、ファイル名の終わりはそのようなパターンでなければなりません。

For this tutorial, we will use a simple database that might be used to support a bookstore application. The database will contain three tables: author, publisher, and book. The first table will contain author information (first and last name). The second table will contain publisher information (name). And the third table will contain book information (title, and ISBN). The author id and publisher id will be foreign keys in the book table. The schema representation for this database is as follows:

このチュートリアルでは、ブックストアのアプリケーションをサポートするために使われるような簡単なデータベースを使いましょう。 このデータベースはauthor、publisher,bookの3つのテーブルを含みます。 1つめのテーブルは、著者の情報(名と姓)を含みます。 2つめのテーブルは出版社の情報(名前)を含みます。 そして、3つめのテーブルは、本の情報(タイトルとISBN番号)を含みます。 著者(autor)のIDと出版社(publisher)のIDは、bookテーブルの外部キーとなります。 このデータベースを表現するスキーマは、次のようになります。

<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<!DOCTYPE database SYSTEM
 "http://jakarta.apache.org/turbine/dtd/database.dtd">

<database
  name="bookstore"
  defaultIdMethod="idbroker">

  <table name="book" description="Book Table">
    <column
      name="book_id"
      required="true"
      primaryKey="true"
      type="INTEGER"
      description="Book Id"/>
    <column
      name="title"
      required="true"
      type="VARCHAR"
      size="255"
      description="Book Title"/>
    <column
      name="isbn"
      required="true"
      type="VARCHAR"
      size="24"
      javaName="ISBN"
      description="ISBN Number"/>
    <column
      name="publisher_id"
      required="true"
      type="INTEGER"
      description="Foreign Key Publisher"/>
    <column
      name="author_id"
      required="true"
      type="INTEGER"
      description="Foreign Key Author"/>
    <foreign-key foreignTable="publisher">
      <reference
        local="publisher_id"
        foreign="publisher_id"/>
    </foreign-key>
    <foreign-key foreignTable="author">
      <reference
        local="author_id"
        foreign="author_id"/>
    </foreign-key>
  </table>
  <table name="publisher" description="Publisher Table">
    <column
      name="publisher_id"
      required="true"
      primaryKey="true"
      type="INTEGER"
      description="Publisher Id"/>
    <column
      name="name"
      required="true"
      type="VARCHAR"
      size="128"
      description="Publisher Name"/>
  </table>
  <table name="author" description="Author Table">
    <column
      name="author_id"
      required="true"
      primaryKey="true"
      type="INTEGER"
      description="Author Id"/>
    <column
      name="first_name"
      required="true"
      type="VARCHAR"
      size="128"
      description="First Name"/>
    <column
      name="last_name"
      required="true"
      type="VARCHAR"
      size="128"
      description="Last Name"/>
  </table>
</database>

Edit project-schema.xml to reflect the above database schema. If you would rather create your own schema file, be sure the filename ends in ‘-schema.xml’, and delete project-schema.xml because Torque will generate an object model for that file as well. Do not delete id-table-schema.xml if you plan on using Torque's IDBroker service, which is used in this tutorial.

project-schema.xmlを編集して、上記データベース・スキーマを反映させて下さい。 あえて独自のスキーマファイルを作成するなら、ファイル名を‘-schema.xml’で終わるように気をつけて作成し、さらにproject-schema.xmlを削除して下さい。 Torqueはproject-schema.xmlからオブジェクトモデルを生成してしまうからです。 このチュートリアルで使っている、TorqueのIDBrokerサービスを使おうとするなら、id-table-schema.xmlを削除しないで下さい。

There are several items of importance to note. The database element's name attribute must be the same as the database name specified by the databaseUrl property in build.properties; likewise, the run-time properties (described in the next section) should also reflect this value. Failure to do so will prevent Torque from creating your database tables (if instructed to do so) or prevent your object model from working properly.

注意すべき重要項目がいくつかあります。 database要素のname属性は、build.propertiesdatabaseUrlプロパティで指定されたデータベース名と同じでなければなりません。 同様に、ランタイムプロパティ(次のセクションで説明)もこの値を反映すべきです。 そうしなければ、(もし、そうすることを指示されても)Torqueがデータベーステーブルを作成できなくなったり、オブジェクトモデルが全然動かなくなったりします。

Another item of importance is the database element's defaultIdMethod attribute. This attribute specifies the default method that Torque will use to generate IDs for primary keys (columns with the primaryKey attribute set to true: book_id, publisher_id, and author_id) in your database tables. There are several possible values:

もうひとつの重要項目は、database要素のdefaultIdMethod属性です。 この属性は、データベースの主キー(カラムのprimaryKey属性がtrueであるbook_id, publisher_id, author_id)のIDを生成するためにTorqueが使うデフォルトのメソッドを指定します。 defaultIdMethodに指定可能な値としては、次のようなものがあります。

Property Description
idbroker Instructs Torque to use its IDBroker service to generate IDs in a database agnostic manner. This is the method that will be used in this tutorial.
データベースごとの方法にとらわれずにIDを生成するIDBrokerサービスを使うことを指定します。
native Instructs Torque to use the underlying database's mechanism to generate IDs (varies per database).
IDの生成に(データベースごとに異なる)基礎的なデータベースメカニズムを使うことを指定します。
none Instructs Torque to not generate IDs. This can be useful in some situations (an example is described below).
IDを生成しないことを指定します。 これはいくつかの場合で(下記に例を挙げます)に役立ちます。
autoincrement This method has been deprecated. Use the native method instead.
このメソッドは、推奨されていません(deprecated)。 替わりにnativeを使って下さい。
sequence This method has been deprecated. Use the native method instead.
このメソッドは、推奨されていません(deprecated)。 替わりにnativeを使って下さい。

The defaultIdMethod selected will be used for all tables in your schema unless an individual table element contains the idMethod attribute, in which case, its value will override the defaultIdMethod. idMethod takes the same values as defaultIdMethod.

スキーマ内の個々のtable要素に、idMethod属性が含まれていないものはすべて、defaultIdMethodで選択した値が使われます。 idMethod属性が含まれている場合は、その値がdefaultIdMethodの値をオーバーライドします。 idMethodが取りうる値は、defaultIdMethodのものと同じです。

One common reason that a table might override the defaultIdMethod is when a table is composed only of foreign keys (i.e. a ‘junction entity’ in database-speak). In this case, all columns should be defined as primary keys because they are all needed to declare a row as unique. However, Torque should not generate primary key IDs for objects in this table because the objects that compose the table already have primary key IDs. Thus, the idMethod attribute of the table must be set to none. For example, if the book table defined above did not have any additional attributes other than a publisher_id and author_id, the schema for the book table should be defined as:

テーブルがdefaultIdMethodをオーバーライド可能である一般的な理由として、テーブルが外部キーだけで構成されている場合があります。 (i.e. データベースの世界で言うところの‘junction entity’。 )この場合、すべての行がユニークであると表明する必要があるため、すべてのカラムが主キーとして定義されているべきです。 しかし、Torqueは、このテーブルのオブジェクトに対して主キーのIDを生成するわけはありません。 そのオブジェクトはすでに主キーのIDを持つテーブルで構成されるからです。 よって、そのテーブルのidMethod要素をnoneにするべきです。 たとえば、上記で定義されているbookテーブルが、publisher_idauthor_idの他に何も属性を持たない場合、そのスキーマはこのように定義されます。

  <table name="book" idMethod="none" description="Book Table">
    <column
      name="publisher_id"
      required="true"
      primaryKey="true"
      type="INTEGER"
      description="Foreign Key Publisher"/>
    <column
      name="author_id"
      required="true"
      primaryKey="true"
      type="INTEGER"
      description="Foreign Key Author"/>
    <foreign-key foreignTable="publisher">
      <reference
        local="publisher_id"
        foreign="publisher_id"/>
    </foreign-key>
    <foreign-key foreignTable="author">
      <reference
        local="author_id"
        foreign="author_id"/>
    </foreign-key>
  </table>

Another common mistake is to forget that XML is case-sensitive. All of the elements and attributes must be specified according to the DTD for the database schema. In addition, you must include the XML declaration and DTD specification in your database schema file. Failure to do so can result it errors.

もうひとつ、よくある間違いとして、XMLがcase-sensitiveである(大文字と小文字を区別する)ことを忘れてしまうことがあります。 すべての要素と属性は、データベーススキーマのDTDに添って指定されていなければなりません。 加えて、XML宣言とDTDの指定を、データベーススキーマファイルに含めなければなりません。 これをきちんと行わないと、エラーとなるでしょう。

Finally, you must also edit (or add if its not present) the name attribute to the database element in id-table-schema.xml. The value should be identical to the value in your database schema file. This will instruct Torque to create id-table in the same database as your schema. Below is the file used in this example:

最後に、id-table-schema.xml内のdatabase要素のname属性を編集(もし存在しない場合は追加)しなければなりません。 この値はデータベーススキーマファイルと同じ値にすべきです。 これはTorqueに、スキーマと同じデータベースにid-tableを作成することを指示します。 以下は、この例題で使われるid-table-schema.xmlファイルです。

<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<!DOCTYPE database SYSTEM
 "http://jakarta.apache.org/turbine/dtd/database.dtd">

<database name="bookstore">
  <table name="ID_TABLE" idMethod="idbroker">
    <column
      name="ID_TABLE_ID"
      required="true"
      primaryKey="true"
      type="INTEGER"/>
    <column
      name="TABLE_NAME"
      required="true"
      size="255"
      type="VARCHAR"/>
    <column
      name="NEXT_ID"
      type="INTEGER"/>
    <column
      name="QUANTITY"
      type="INTEGER"/>
    <unique>
      <unique-column name="TABLE_NAME"/>
    </unique>
  </table>
</database>

Torque uses the database schema files to generate your object model and Java classes to support it. In addition, Torque generates SQL that can be used to create your databases and tables from these schemas. In the next section, we will conclude the configuration of Torque by editing the Torque run-time properties. For additional information on the XML elements and attributes, please refer to the Torque Schema Reference.

Torqueは、オブジェクトモデルとそれを扱うJavaクラスを生成するためにデータベーススキーマファイルを使用します。 加えてTorqueは、スキーマファイルからデータベースとテーブルを作成するSQLを生成します。 次のセクションでTorqueランタイムプロパティを編集し、Torqueの設定を締めくくりましょう。 XMLの要素と属性についてのさらなる情報は、Torqueスキーマリファレンスを参照して下さい。

Torque Run-Time Properties

Torqueランタイムプロパティ

The last step in the configuration of Torque are the Torque run-time properties. As the name suggests, these properties are used when your application is executing the object model code generated by Torque. The run-time properties control logging and database parameters such as drivers, usernames, and passwords. These properties can be saved in any file because your application must explicitly initialize Torque (as you'll see later in this document).

Torqueの設定の最後のステップは、Torqueランタイムプロパティです。 名前が示すとおり、これらのプロパティはTorqueが生成したオブジェクトモデルを、アプリケーションが実行する時に使われます。 ランタイムプロパティは、ログ出力や、ドライバ、ユーザ名、パスワードのようなデータベースのパラメータを管理します。 これらのプロパティは、アプリケーションが明示的にTorqueを初期化しなければならないため、複数のファイルに保存されます。 (のちほど、このドキュメントで見ていきます。)

There is a sample run-time properties file included in the Torque distribution called Torque.properties located in the torque/schema directory. However, for simplicity, we'll just create our own. Again, this tutorial will guide you through the bare minimum to get your application up and running. For more information regarding the Torque run-time properties, refer to the comments in the sample file included in the distribution. Create a new file called Torque.properties in the top-level torque directory (to avoid overwriting the sample property file) and add the following lines to it:

これはtorque/schemaディレクトリにあるTorque.propertiesという、Torqueディストリビューションに含まれるランタイムプロパティファイルのサンプルです。 これは簡単なものですが、自分で作成しなければなりません。 繰り返しますが、このチュートリアルは、アプリケーションをセットアップして動かすための最低限のガイドです。 Torqueランタイムプロパティに関するさらなる情報には、ディストリビューションに含まれるサンプルファイルのコメントを参照して下さい。 Torque.propertiesを(サンプルのプロパティファイルを上書きせずに)torqueディレクトリの直下に作成して、そのファイルに次の行を追加しましょう。

log4j.rootCategory = DEBUG, default
log4j.appender.default = org.apache.log4j.FileAppender
log4j.appender.default.file = ./torque.log
log4j.appender.default.layout = org.apache.log4j.SimpleLayout

torque.database.default=bookstore
torque.database.bookstore.driver = org.gjt.mm.mysql.Driver
torque.database.bookstore.url = jdbc:mysql://127.0.0.1/bookstore
torque.database.bookstore.username = user
torque.database.bookstore.password = password
  

Property プロパティ Description 説明
log4j.rootCategory Torque uses Log4J for a logging. This parameter configures the Log4J system to log all messages (debug, info, warn, error, and fatal).
TorqueはロギングにLog4Jを使います。 このパラメータは、すべてのメッセージ(debug, info, warn, error, そして fatal)をログ出力するするたように、Log4Jシステムを設定しています。
log4j.appender.default Configures Log4J to send all logging messages to a file in the filesystem. Log4J could just as easily send all logging to a syslog server.
ファイルシステム上のあるファイルにすべてのログメッセージを送るように、Log4Jを設定しています。 Log4Jは、簡単にsyslogサーバーにログを送ることができます。
log4j.appender.default.file The name of the file where messages are logged. This is relative to the starting point of the JVM.
メッセージのログを残すファイルのファイル名です。 JVMの起動地点からの相対パスです。
log4j.appender.default.layout Log4J logs messages using a layout. Layouts can be very simple or complicated. This tutorial uses the very rudimentary SimpleLayout.
Log4Jはlayoutを使ってメッセージのログを取ります。 Layoutは、とてもシンプルなものだったり、複雑ものだったりします。 このチュートリアルでは、とても初歩的なSimpleLayoutを使います。
torque.database.default Torque has the ability to use multiple databases. This command specifies which database is to be used as the default.
Torqueでは複数のデータベースを使うことができます。 このコマンドはどのデータベースをデフォルトで使用するか指定します。
torque.database.bookstore.driver The JDBC database driver to use when connecting to your database.
データベースと接続するのに使われるJDBCドライバです。
torque.database.bookstore.url The URL that will be used to access your database. Torque's generated object model will perform all database operations using this URL. This value should reflect the database name specified in your database schema file (see the database element's name attribute).
データベースにアクセスするために使われるURLです。 生成されたTorqueのオブジェクトモデルはこのURLを使用してデータベース操作を実行します。 この値は、データベーススキーマで指定したデータベース名を反映すべきです。 (database要素のname属性を参照。 )
torque.database.bookstore.username The username that has sufficient privileges to access your database. This user does not require privileges to create and drop tables, unlike the username that was specified in the Torque build.properties.
データベースへのアクセス権限を持つユーザ名です。 Torqueのbuild.propertiesで指定したユーザ名と違い、このユーザに、テーブルを作成、削除する権限は必要ありません。
torque.database.bookstore.password The password for the specified username.
指定したユーザのパスワードです。

It is worth re-iterating that these run-time properties are not used by Torque when generating your object model and creating your database. They are used only by the application utilizing the Torque-generated object model classes at run-time.

オブジェクトモデルを生成し、データベースを作成するときには、Torqueはこれらのランタイムプロパティを使わないことを繰り返して言っておきます。 これらは、Torqueが作成したオブジェクトモデルクラスを利用するアプリケーションによってのみ、動作時に使われます。

That completes the configuration of Torque. You are now ready to start building your object model and creating your database.

以上でTorqueの設定が完了しました。 これで、オブジェクトモデルをビルドし、データベースを作成する準備ができました。

Step 3: Invoking Torque

Step 3: Torqueの呼び出し

With the configuration of Torque completed, you can now generate the object model to support your database, and optionally create your database and all of its associated tables. As mentioned earlier in this tutorial, Torque utilizes Ant to perform these tasks. Each of these tasks is covered in the following sections.

Torqueの設定が終われば、データベースを扱うするオブジェクトモデルを生成し、オプションでデータベースとすべての関連テーブルを作成することができます。 このチュートリアルの前の部分で触れたとおり、Torqueはこれらのタスクを実行するためにAntを利用します。 これらの各タスクについて、次のセクションから説明します。

Generating the Object Model and Associated SQL

オブジェクトモデルと関連SQLの生成

The generation of your object model will produce Java source files that can be used to represent your database. These classes enable you to create, edit, delete, and select objects that represent rows in your database tables. In addition, Torque will generate SQL to create your database tables (you have the option of executing the SQL as demonstrated later in this tutorial).

オブジェクトモデルの生成とは、データベースを表現するために使用されるJavaソースファイルを作成することです。 これらのクラスによって、データベーステーブルの行を表現するオブジェクトを生成、編集、削除、取得できるようになります。 加えて、Torqueは、データベースのテーブルを作成するSQLを生成します。 (SQL実行の選択肢については、このチュートリアルの後の部分で説明しています。 )

The object model consists of four classes for each table in your schema. For example, the author table, defined in this tutorial, will result in the following four classes: Author, AuthorPeer, BaseAuthor, and BaseAuthorPeer (a discussion on the use of these classes is deferred until we write our sample application).

オブジェクトモデルは、スキーマ内のテーブルそれぞれに対して4つのクラスで構成されています。 たとえば、このチュートリアルで定義されているAuthorテーブルからは、結果としてAuthorAuthorPeerBaseAuthorBaseAuthorPeerの4つのクラスが生成されます。 (これらのクラスの使用に関する議論は、サンプルアプリケーションを書くときまでとっておきます。)

To generate your object model and the associated SQL, type the following command in the top-level torque directory:

オブジェクトモデルと、関連するSQLを生成するために、torqueディレクトリの直下で次のコマンドを叩いて下さい。

ant -f build-torque.xml

Upon a successful build, indicated by the ‘BUILD SUCCESSFUL’ message, you will find a new torque/src directory. It is here that you will find the generated Java classes and generated SQL.

‘BUILD SUCCESSFUL’メッセージが表示され、ビルドに成功すると、新しくtorque/srcディレクトリができたと思います。 ここが、生成されたJavaクラスと生成されたSQLがある場所です。

The Java classes are located in the java directory and will be in a directory hierarchy matching that of the targetPackage you specified in your Torque build.properties. These are the files that will be compiled into your object model classes.

javaクラスは、javaディレクトリにあり、Torqueのbuild.propertiesで指定したtargetPackageプロパティの値と階層的に合うディレクトリにあるでしょう。 これらのファイルは、オブジェクトモデルのクラスへコンパイルされるものです。

The SQL files are located in the sql directory. For each database schema in your torque/schema directory, there will be a corresponding file with a .sql extension instead of .xml extension. The contents of these files are the SQL commands that can be used to manually or automatically (see next section) create your database tables.

SQLファイルはsqlディレクトリにあります。 torque/schemaディレクトリにある拡張子が.xmlの各データベーススキーマに対して、拡張子が.sqlであるファイルがあると思います。 これらのファイルの内容は、マニュアルまたは自動的に(次のセクション参照)、データベースのテーブルを作成するために使われるSQLコマンドです。

If you encounter errors while building, it is more than likely a formatting error of your database schema file. Check the format of the file and make sure it conforms to the Torque Schema Reference.

ビルド中にエラーが起きた場合、おそらくデータベーススキーマファイルのフォーマットエラーだと思われます。 そのファイルのフォーマットをチェックして、それがTorqueスキーマリファレンスに従っているか確認しましょう。

Creating the Database and Tables

データベースとテーブルの作成

As mentioned previously, Torque can automatically create your database and all of the associated tables for you. However, you must first make sure that the appropriate database driver (the one you defined in build.properties) is in your classpath so that Torque can connect to your database and execute the generated SQL commands. The easiest way to accomplish that is to add your database driver to the torque/lib directory. Ant's build file automatically adds all of the jar files in this directory to its classpath.

前に説明したように、Torqueは自動的にデータベースとすべての関連テーブルを作成してくれます。 しかしまず最初に、Torqueがデータベースに接続し、生成したSQLコマンドが実行できるように、適切な(build.propertiesで定義した)データベースドライバがクラスパスに含まれているか確認しなければなりません。 それを成し遂げるために最も簡単な方法は、torque/libディレクトリにデータベースドライバを追加することです。 Antのビルドファイルが、このディレクトリにあるすべてのjarファイルを自動的にクラスパスに追加してくれます。

Note: Torque will drop the database and tables that it is about to create if they exist! You should skip this step if you are working with an existing database full of data.

注:Torqueは、作成しようとしているデータベースやテーブルがすでに存在していた場合、それを削除してしまいます。 データが詰まっている現在のデータベースを使用するなら、このステップはスキップすべきです。

To create your database, type the following command in the top-level torque directory:

データベースを作成するには、torqueディレクトリ直下で、次のコマンドを叩いて下さい。

ant -f build-torque.xml create-db

To create your tables, type the following commands in the top-level torque directory:

テーブルを作成するには、torqueディレクトリ直下で、次のコマンドを叩いて下さい。

ant -f build-torque.xml id-table-init-sql
ant -f build-torque.xml insert-sql

Note: if this tutorial had not utilized Torque's idbroker method (as described earlier), it would not have been necessary to execute the id-table-init-sql target.

注:もし、このチュートリアルで(前出の)Torqueのidbrokerメソッドを使っていなければ、id-table-init-sqlターゲットを実行する必要はありません。

Success will be indicated by the ‘BUILD SUCCESSFUL’ message. You can also validate this by checking your database. For example, the bookstore-schema.xml and id-table-schema.xml, defined in this tutorial, should have created a database called bookstore, with the following tables: ID_TABLE, author, book, and publisher.

‘BUILD SUCCESSFUL’メッセージが表示されたら、ビルド成功です。 データベースをチェックすることでこれを確認することができます。 例えば、このチュートリアルで定義されているbookstore-schema.xmlid-table-schema.xmlからは、ID_TABLEauthorbookpublisherというテーブルが存在するbookstoreデータベースが作られるはずです。

If you encounter errors while creating your database, it is more than likely a misconfiguration of your build.properties. Another common problem is that the user specified in the build.properties does not have sufficient privilege to create databases and tables. In either case, refer to the section above that explains the build.properties file.

もしデータベース作成中にエラーが起きた場合は、build.propertiesの設定ミスが考えられます。 よくある別の問題としては、build.propertiesで指定したユーザ、データベースとテーブルを作成する権限がないことです。 どちらのケースについても、前のbuild.propertiesファイルを説明しているセクションを参照して下さい。

Now that you have generated all of your object model classes and created your database, you are now ready to build your first Torque application.

これですべてのオブジェクトモデルを生成し、データベースを作成し終え、初めてのTorqueアプリケーションをビルドする準備ができました。

Step 4: Writing a Sample Application

Step 4: サンプルアプリケーションの記述

Congratulations, you have finally reached the fun the part of this tutorial. This is where you'll discover the power of Torque. Be warned, you'll never want to write another SQL statement ever again!

おめでとうございます。 ついに、このチュートリアルの面白い部分にたどり着きました。 ここがTorqueの威力を発見する場所です。 もう二度とSQLの構文を書きたくないと思ってしまうでしょうから、気をつけて下さいね。

As mentioned earlier, when Torque created your object model, it created four 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, BaseBook, and BaseBookPeer.

前の部分で触れたとおり、Torqueがオブジェクトモデルを作成するときに、データベーススキーマで定義されているテーブルそれぞれに4つのJavaクラスを作成します。 例えば、先ほどのデータベーススキーマで定義されていたbookテーブルからは、BookBookPeerBaseBookBaseBookPeerのクラスが生じます。

Book and BookPeer are subclasses of BaseBook and BaseBookPeer respectively. The two Base classes (BaseBook and BaseBookPeer) contain Torque-generated logic and should not be modified because Torque will overwrite your changes if you happen to generate your object model again (via ant). Any business logic that you might want to add should be placed in the Book and BookPeer classes. This is covered later in the tutorial.

BookBookPeerはそれぞれ、BaseBookBaseBookPeerのサブクラスです。 二つのBaseクラス(BaseBookBaseBookPeer)は、Torqueが生成したロジックを含んでいて、それを修正するべきではありません。 もし、たまたま(antで)再度オブジェクトモデルを生成してしまったら、Torqueは変更を上書きしてしまうからです。 追加しようとするビジネスロジックはどれも、BookBookPeerクラスに置くべきです。 このことに関しては、このチュートリアルの後の部分で触れます。

You might be asking yourself, what is the difference between the Peer classes (BookPeer and BaseBookPeer) and their counterparts (Book and BaseBook), also known as Data Objects? The Peer classes “wrap” their associated database tables and provide static methods to manipulate those tables such as doSelect, doInsert, and doUpdate. Data Objects, on the other hand, “wrap” individual rows within those tables and provide getters/mutators for each column defined in those tables as well as the convenient save method. Both Peer and Data Objects 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 Peers HOWTO. An example of adding logic to both the Peer and Data Objects is presented later in the tutorial.

きっとあなたは、これらのPeerクラス(BookPeerBaseBookPeer)と、データオブジェクトと言われるもう一方のもの(BookBaseBook)では、何が違うんだと自問するかもしれません。 Peerクラスは、関連するデータベーステーブルを“ラップ”し、doSelectdoInsertdoUpdateのような、関連テーブルを操作するstaticメソッドを提供します。 一方、データオブジェクトはこれらのテーブル内の個々の行を“ラップ”し、便利なsaveメソッドと同様、それらのテーブルで定義された各カラムに対するゲッター/ミューテイターを提供します。 Peerクラスとデータオブジェクトのどちらも、データベーススキーマで定義されたテーブルと1対1でマッピングされます。 Peerクラスとデータオブジェクトに関するさらに深い話は、Peers HOWTOを参照して下さい。 Peerとデータオブジェクトの両方にロジックを追加する例は、このチュートリアルの後の方にあります。

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.

さて、ここまででTorqueが生成したオブジェクトモデルの基本には触れました。 このセクションの残りでソースコードの小さな断片で示されたTorqueでデータベースへのインサート、セレクト、アップデート、デリートする方法について記述します。 これらのソースコードの断片は、オブジェクトモデルを拡張する方法についての話題の後で全体が明らかになるサンプルアプリケーションの一部です。 最後に、コンパイルして起動する方法の解説を詳しく述べます。

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).

Torqueを使うとデータベースに簡単に行を挿入することができます。 単純に新しいデータオブジェクトをインスタンス化し、テーブルのカラム名にちなんだ名前のミューテイターを使ってプロパティをセットし、そして、そのデータオブジェクトのsaveメソッドを呼び出します。 注:Torqueは、特に指定しなければ、オブジェクトの主キーのIDを自動的に振ってくれるので、自分でするセットする必要はありません。 (前述のデータベーススキーマの設定を参照。)

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. Thats it. The following is from the sample application:

例えば、(このチュートリアルのデータベーススキーマで定義されている)authorテーブルに新しい行を挿入するには、新しくAuthorオブジェクトをインスタンス化し、そのオブジェクトのsetFirstNameメソッドとsetLastNameメソッドを適当な値を指定して呼び出し、そして、saveメソッドを呼びます。 それだけなのです。 以下のソースは、サンプルアプリケーションから抜粋したものです。

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

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

It is also possible to insert a row using the Peer class directly instead of invoking the save method of your Data Object. Recall, the Peer class provides static methods to perform operations on a table. One of these operations is the ability to insert rows via the doInsert method. The Data Object's save method actually calls doInsert for you (or doUpdate if the object is not new and must be updated).

データオブジェクトのsaveメソッドの代わりに、直接Peerクラスを使って行を挿入することも可能です。 Peerクラスは、テーブルの操作を実行するためのstaticメソッドを提供するということを思い出して下さい。 これらの操作のうちの一つが、doInsertメソッドによる行の挿入です。 このデータオブジェクトのsaveメソッドは実際にはdoInsertメソッドを(もしくは、そのオブジェクトが新しく生成されたものではなく、updateすべきものであればdoUpdateを)呼んでいます。

For example, you can use AuthorPeer.doInsert as an alternative method to insert a new row in the author table. The following is from the sample application:

例えば、authorテーブルに新しい行を挿入するための別の方法として、AuthorPeer.doInsertメソッドを使うことができます。 以下のソースは、サンプルアプリケーションから抜粋したものです。

Author stevens = new Author();
stevens.setFirstName("W.");
stevens.setLastName("Stevens");
AuthorPeer.doInsert(stevens);

It should also be noted for completeness that doInsert can be passed a Criteria object (discussed in the next section) instead of a Data Object (see the Javadoc for details). However, the most common method for the insertion of rows in a table is via the save method of the Data Object rather than directly using the Peer's doInsert method.

仕上げとして書いておくと、doInsertは、データオブジェクトの代わりに(次のセクションで説明する)Criteriaオブジェクトが渡されることもあります。 (詳細はJavadocを参照して下さい。 )とはいえ、テーブルに行を挿入するもっとも一般的な方法は、PeerクラスのdoInsertメソッドを直接呼ぶ方法ではなく、データオブジェクトの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.

外部キーが含まれるテーブルへの行の挿入も簡単です。 Torqueは、オブジェクトモデルの外部キーを表す、特定のデータオブジェクトクラスのミューテイターを作成します。 このメソッドの名前はsetTableで、Tableは(データベースで定義されている)外部キーのテーブルの名前です。 このメソッドを適当なリファレンスを指定して呼ぶことで、Torqueは自動的に外部キーを作成し、挿入してくれます。

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:

例えば、(データベーススキーマで定義されている)bookテーブルには2つのauthor_idpublisher_idの外部キーが含まれています。 このテーブルに行を挿入するには、外部キーを(setAuthorIdsetPublisherIdを使って)明示的にセットする代わりに、setAuthorsetPublisherを使ってAuthorPublisherデータオブジェクトのリファレンスを渡す、上記のような処理を行います。 前の部分ですでに生成されたオブジェクトを組み合わせている以下のコードでは、両方の方法を説明しています。

/*
* 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.

見てわかるとおり、Torqueのオブジェクトモデルを使えば、とても簡単にデータベースに行を挿入することができます。

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 Critieria 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 vector of Data Objects representing the rows of data selected. To use these Data Objects in your application, you must cast them to the appropriate type in your object model.

データベースから行をセレクトするには、行を挿入するのと同じくらい簡単です。 テーブルに関連したPeerクラスには、テーブルからデータを抜き出すために使われるdoSelectというメソッドが定義されています。 doSelectの論点は、Criteriaオブジェクトです。 データベースからデータを選択するときに使われる判断基準(criteria)を指定するのがこのオブジェクトです。 問合せの結果、doSelectは選択されたデータの行を表すデータオブジェクトのvectorを返します。 アプリケーション内でこれらのデータオブジェクトを使うには、オブジェクトモデルの適切な型にキャストする必要があります。

For example, to select all of the rows from the book table that were inserted in the previous section, you must first create an 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:

例えば、bookテーブルから前のセクションで挿入されたすべての行をセレクトするには、最初にCriteriaオブジェクトを作成しなければなりません。 テーブルからすべてをセレクトしたいので、判断基準は指定しません。 (i.e. 内部で使われるSELECT文にWHERE句はない) 以下で説明されているように、問合せを実行するには、空のCriteriaオブジェクトが渡されます。

Criteria crit = new Criteria();
List v = BookPeer.doSelect(crit);

The results are stored in a vector 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):

結果はvectorに蓄えられ、テーブルから照会した個々のBookオブジェクトにアクセスするために繰り返し(iterate)されます。 次のコードは、Bookを標準出力に書き出すコードです。 (もっといいアプローチが後にあります。)

Iterator i = v.iterator();
while (i.hasNext())
{
Book book = (Book) i.next();
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.

上記の例では、getAuthorgetPublisherを呼ぶと、オブジェクトモデルが自動的にAuthorPublisherデータオブジェクトを照会してくれたことに気づいたでしょう。 これは、各テーブルに対して裏側で走る追加SQLクエリーの結果です。 getAuthorは2呼ばれていますが、Authorのすべてのカラムは裏側で走るクエリーでセレクトされているので、SQLクエリーは一度しか生じていません。

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). A single query using a join would be much more efficient. As a convenience, Torque generates the following protected methods in the BasePeer classes whose tables contain foreign-keys: doSelectJoinTable 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. As a reminder, to use these convenience methods, you must provide public members to BookPeer for clients because they are protected in BaseBookPeer. Unfortunately, Torque does not generate a doSelectJoinAll or doSelectJoinAuthorPublisher method. Those are left to the reader as an exercise to implement in the BookPeer class.
しかしながら、外部キーによってすべてのテーブルのデータオブジェクトを問合せて組み合わせる上で、これがもっとも効率のいいメソッドというわけではありません。 (1回の問合せを行い、さらに、各行に対して2回の追加クエリが発行される) joinを使った1回の問合せの方がはるかに効率的です。 外部キーを含むテーブルのBasePeerクラスに、Torqueは次のprotectedメソッドを生成します。 それは、doSelectJoinTableで、Tableの部分は外部キーが指すテーブル名となります。 このメソッドは、(1回のjoinクエリで)効率よくデータベースの問合せを行い、自動的にすべてのデータオブジェクトを組み合わせます。 これは、外部キーのデータオブジェクトを照会するときに発行される追加のクエリを取り除きます。 例えば、doSelectJoinAuthordoSelectJoinPublisherは、BookPeerを継承したBaseBookPeerクラス内に生成されます。 注意すべきは、BaseBookPeer内でprotectedなので、これらの便利なメソッドを使うには、クライアント(呼び出し側)のためにBookPeerpublicメンバを用意する必要があります。 不運なことにTorqueは、doSelectJoinAlldoSelectJoinAuthorPublisherメソッドは生成しません。 これらは、BookPeerクラスに実装する、読者に残された課題です。

To select a specific Book from the table, create a Criteria object (or just reuse the previous one) and use the add method to specify some criteria. Specifying criteria 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:

特定のBookをテーブルからセレクトするには、Criteriaオブジェクトを作成(または、先ほどのものを再利用)し、判断基準を指定するためにaddメソッドを使います。 判断基準の指定は、単に(Peerクラスにstatic定数として定義されている)カラム名と、一致して欲しい値を選ぶことです。 そして、ISBNが‘0-618-12902-2’であるbookをセレクトするには、単にこのようにします。

Criteria crit = new Criteria();
crit.add(BookPeer.ISBN, "0-618-12902-2");
List v = 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 Criteria HOWTO.

このセクションでは、Criteriaオブジェクトの表面をすくっただけです。 Criteriaはとても単純なクエリから、とても複雑なクエリまでを指定するために使われます。 Criteriaに関するもっと深い説明は、Criteria HOWTOを参照して下さい。

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.

テーブルの行を更新するには、1つ以上のミューテイターを呼び出して、行を表すデータオブジェクトのプロパティを1つ以上変更し、そのsaveメソッドを呼ぶだけのことです。 ミューテイターを呼んだとき、そのデータオブジェクトは変更されたことを示す内部のフラグをセットします。 saveメソッドが呼ばれたとき、データベース操作を実行するためにPeerのdoInsertdoUpdateのどちらを呼ぶかを決める目的で、このフラグをチェックします。

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

例えば、以前作成された‘Effective Java’の本の著者を変更するには、単純にこうします。

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

Alternatively, instead of calling the Data Object's save method, the Peer's doUpdate method may be called directly with a Data Object that has been modified as the argument. This is illustrated in the following fragment of code that changes the author of the ‘TCP/IP Illustrated’ book:

データオブジェクトのsaveメソッドの替わりに、[as the argument]変更されているデータオブジェクトを指定して、直接PeerのdoUpdateメソッドが呼ばれるかもしれません。 この方法は、‘TCP/IP Illustrated’の本の著者を変更している、次のコード断片で説明されます。

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

Again, for completeness, doUpdate could have been passed a Criteria object to update a row (see the Javadoc for details). However, the most common method to update rows in a table is via the Data Object's save method rather than directly using the Peer's doUpdate method.

再び仕上げとして書いておきますが、行を更新するためにdoUpdateCriteriaが渡されることがあります。(詳細はJavadocを参照。) とはいえ、テーブルの行を更新するためのもっとも一般的な方法は、直接PeerのdoUpdateを使う方法ではなく、データオブジェクトの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.

テーブルから行を削除することも同じくらい簡単です。 Peerクラスには、この目的のために使われるstaticメソッドdoDeleteが定義されています。 他のPeerのメソッドと同じように、doDeleteには、削除する行を指定するCriteriaオブジェクトかデータオブジェクトが渡されます。 気をつけなければならないのは、データオブジェクトには行を削除するためのメソッドがないということです。

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.

例えば次のコードでは、doDeleteの両方の形式を使って、このチュートリアルの過程でインサートされた3つのテーブルのすべての行を削除しています。 まず始めに、指定したCriteriaによってBookを削除し、それから、直接データオブジェクトを渡して著者(author)と出版社(publisher)を削除しています。

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.

注:外部キーを含むテーブルから行を削除とき、テーブルから外部キー(が指すデータ)を自動的に削除しません。 外部キー(が指すデータ)を削除したい場合は、上の例で示すように、明示的に行わなければいけません。 例えば、bookテーブルを削除してもauthorpublisherテーブルの対応する行は自動的には削除されません。

The Gory Details (not for the faint)
血みどろな詳細(気絶注意)
It should also be noted that doDelete does not construct its WHERE clause in a similar manner as the doSelect method. doDelete processes Criteria in a more primitive fashion. Specifically, Criteria assembled using the and and or methods (not covered in this tutorial) are effectively ignored. In addition, passing an empty Criteria to doDelete will not delete all of the rows from a table. In summary, you cannot assume that a Criteria object which successfully selects rows from a table via doSelect will delete those rows if passed to doDelete. In the future, doDelete may be modified to be consistent in the handling of Criteria objects.
doDeleteは、doSelectメソッドと同様のやりかたでWHERE句を組み立てることはしないということを触れておきます。 doDeleteは、もっと原始的なやりかたでCriteriaを処理します。 具体的に言うと、andorメソッド(このチュートリアルでは触れません)を使っているCriteriaは、事実上無視されています。 加えて、空のCriteriadoDeleteに渡しても、テーブルからすべての行を削除するわけではありません。 まとめると、doSelectではうまくテーブルから行をセレクトするCriteriaオブジェクトでも、doDeleteに渡してそれらの行を削除できるとは言えません。 将来、doDeleteは、Criteriaの扱いに矛盾しないように修正されるかもしれません。

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 four classes for each table defined in the database schema. Two of these classes (the Base Data Object and Base Peer class) contain Torque-generated logic while the other two 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.

このセクションでは、Peerとオブジェクトモデルの両方のクラスに機能を追加する例を提供します。 ご存知のとおり、Torqueはデータベーススキーマの各テーブルに対して、4つのクラスを生成しました。 この内の2つのクラス(BaseデータオブジェクトとBasePeerオブジェクト)には、Torqueが生成したロジックが含まれていますが、他の2つはビジネスロジックを加えるために使う空のサブクラスです。 今に至っては、これらのクラスに追加してもいいロジックの種類についてのまともな理解をもっているでしょう。 オブジェクトモデルを再生成した場合、誤ってBaseクラスに追加してしまった変更をTorqueは上書きしてしまいますが、Baseクラスではないクラスに行った変更は上書きされないということを心に留めておいて下さい。

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, which are located in a directory hierarchy matching that of the targetPackage you specified in your Torque build.properties:

オブジェクトモデルに行う最初の変更は、データモデルに適切なtoStringメソッドを与えることです。 このメソッドは、アプリケーションの中核に不必要なコードを追加することなく、データオブジェクトを表示するために使われるでしょう。 次のコードは、Torqueのbuild.propertiesで指定したtargetPackageと階層が一致するディレクトリにあるBookAuthorPublisherクラス修正したものです。

// Book.java
public class Book
  extends com.kazmier.om.BaseBook
  implements Persistent
{
  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 (Exception ignored)
    {
    }
    return sb.toString();
  }
}

// Author.java
public  class Author
  extends com.kazmier.om.BaseAuthor
  implements Persistent
{
  public String toString()
  {
    return getLastName() + ", " + getFirstName();
  }
}

// Publisher.java
public  class Publisher
  extends com.kazmier.om.BasePublisher
  implements Persistent
{
  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 Peers Howto) 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:

次に行う変更は、Peerクラスに対するものです。 便利がいいように、(Peers Howtoでの提案をもとづいて)テーブル内のすべてのデータオブジェクトを返すdoSelectAllメソッドを加えることです。 次のコードは、データオブジェクトと同じディレクトリにあるBookPeerAuthorPeerPublisherPeerクラスを修正したものです。

// BookPeer.java
import org.apache.torque.util.*;

public class BookPeer
  extends com.kazmier.om.BaseBookPeer
{
  public static List doSelectAll() throws Exception
  {
    Criteria crit = new Criteria();
    return doSelect(crit);
  }
}

// AuthorPeer.java
import org.apache.torque.util.*;

public class AuthorPeer
  extends com.kazmier.om.BaseAuthorPeer
{
  public static List doSelectAll() throws Exception
  {
    Criteria crit = new Criteria();
    return doSelect(crit);
  }
}

// PublisherPeer.java
import org.apache.torque.util.*;

public class PublisherPeer
  extends com.kazmier.om.BasePublisherPeer
{
  public static List doSelectAll() throws Exception
  {
    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.

次のコードはサンプルのブックストアアプリケーションをまるごと示したものです。 このチュートリアルをたどっている人なら、とても見慣れた感じがするでしょう。 実際、前のセクションでオブジェクトモデルに追加した新しい機能を使用しているという例外があるが、ほとんど前出のコードと同一のものです。

package com.kazmier;

import java.util.*;
import com.kazmier.om.*;
import org.apache.torque.Torque;
import org.apache.torque.util.Criteria;

public class Bookstore
{
  public static void main(String[] args)
  {
    try
    {
      /*
       * Initializing Torque
       * Torqueの初期化。
       */
      Torque.init("Torque.properties");

      /*
       * Creating new objects.  These will be inserted
       * into your database automatically when the
       * save method is called.
       * オブジェクトの生成。
       * saveメソッドが呼ばれたとき、このオブジェクトが
       * データベースに挿入されます。
       */
      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).
       * データベースからすべての本をセレクトし、
       * BookPeerで定義されたヘルパーメソッド(doSelectAll)を使って、
       * 標準出力に結果を表示する。
       */
      System.out.println("Full booklist:\n");
      List 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.add(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.
       * データを更新する。
       * これらの行は、2つの本の著者を交換します。
       * 結果を確認するために標準出力にbooklistを表示しています。
       */
      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.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);

      /*
       * Deleting data by passing Data Objects instead of
       * specifying criteria.
       * 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.
   * 標準出力にbooklistを表示するためのヘルパメソッド。
   */
  private static void printBooklist(List booklist)
    throws Exception
  {
    Iterator i = booklist.iterator();
    while (i.hasNext())
    {
      Book book = (Book) i.next();
      System.out.println(book);
    }
  }
}
  

Save this code in the torque/src/java directory hierarchy with a filename of Bookstore.java. The above example must be placed in torque/src/java/com/kazmier directory because of its package definition. Your application might go elsewhere depending on the package that you've selected.

このコードを、torque/src/javaのディレクトリ階層に、Bookstore.javaというファイル名で保存して下さい。 パッケージ宣言があるためtorque/src/java/com/kazmierディレクトリに、上記の例を置いて下さい。 選んだパッケージ名によって、他の場所になるかもしれません。

Compiling and Running

コンパイルと実行

Now that you've generated your object model with Torque, and created a sample application, you are now ready to compile everything. Again, Ant is used to control the build process. To compile, type the following in the Torque top-level directory:

Torqueのオブジェクトモデルを生成し、サンプルアプリケーションを作成したので、これですべてをコンパイルする準備が整いました。 ビルド処理を制御するために再びAntを使用します。 コンパイルするにはTorqueのトップディレクトリで次のコマンドを叩いて下さい。

ant -f build-torque.xml compile

If you've done everything correctly, this should build without any errors. All of the resulting Java class files are placed in the torque/bin/classes directory. Should you encounter errors, go back and review your application code.

すべて正しく行っていれば、エラーが出ずにビルドを行うはずです。 torque/bin/classesディレクトリに、すべてのJavaクラスファイルが生成されます。 エラーが起こったら、戻ってアプリケーションのコードを見直して下さい。

Before you run the sample application, you must first set your classpath (this was done automatically for you via Ant's build file when you compiled). The classpath must include: all of the jars in the torque/lib directory, the driver for your database, and all of your application and object model classes located in torque/bin/classes.

サンプルアプリケーションを起動する前に、クラスパスを最初に設定する必要があります。 (これは、コンパイル時にAntのビルドファイルによって自動的に行われます。) クラスパスはtorque/libディレクトリにあるすべてのjarファイル、データベースのドライバ、torque/bin/classesにあるすべてのアプリケーションとオブジェクトモデルのクラスを含めなければいけません。

An easy way to set your classpath (if you're using a bourne-shell or one of its derivatives on a un*x-based system) is to type the following in the top-level Torque directory (first add your database driver to the torque/lib directory if you haven't already):

クラスパスを設定する簡単な方法は、(un*xベースのシステム上で、bourneシェルやその派生物のどれかを使っているなら)次のコマンドをTorqueディレクトリ直下で叩いて下さい。 (データベースドライバがなければ、最初にtorque/libディレクトリに追加してから行います。 )

  [kaz@coco torque]$ CLASSPATH=bin/classes
  [kaz@coco torque]$ for i in lib/*
  > do
  > CLASSPATH=$CLASSPATH:$i
  > done
  [kaz@coco torque]$ export CLASSPATH

With your classpath set, you are now ready to finally run the application. From the top-level directory with your Torque run-time properties, type the following, replacing the name of the class with your class:

クラスパスをセットしたら、ついにアプリケーションを起動する準備ができました。 Torqueのランタイムプロパティファイルがあるトップディレクトリで、クラス名を自分のクラス名に変えた上で、次のコマンドを打ち込んで下さい。

  java com.kazmier.Bookstore

If all goes well, you should see the following output:

うまくいくと、次の出力が得られます。

  Full booklist:

  Title:    Effective Java
  ISBN:     0-618-12902-2
  Publisher:  Addison Wesley Professional
  Author:   Bloch, Joshua

  Title:    TCP/IP Illustrated, Volume 1
  ISBN:     0-201-63346-9
  Publisher:  Addison Wesley Professional
  Author:   Stevens, W.

  Booklist (specific ISBN):

  Title:    TCP/IP Illustrated, Volume 1
  ISBN:     0-201-63346-9
  Publisher:  Addison Wesley Professional
  Author:   Stevens, W.

  Booklist (authors swapped):

  Title:    Effective Java
  ISBN:     0-618-12902-2
  Publisher:  Addison Wesley Professional
  Author:   Stevens, W.

  Title:    TCP/IP Illustrated, Volume 1
  ISBN:     0-201-63346-9
  Publisher:  Addison Wesley Professional
  Author:   Bloch, Joshua

  Booklist (should be empty):
  

If your application throws an exception, it could be for one of many reasons, most of which are not very descriptive unfortunately. For example, mistyping the username or password in your Torque run-time properties file results in a NullPointerException, as do many other types of errors. Do not be discouraged if your application does not run the first time. Carefully retrace all of the steps outlined in this tutorial. If you are still not able to get your application to run, use the Turbine mailing list to your advantage.

アプリケーションが例外をスローした場合、それは多くの原因のうちの一つによるものなのでしょうが、ほとんどは不幸にも記述的ではありません。 例えば、Torqueランタイムプロパティファイルでユーザ名とパスワードをタイプミスした場合、多くの他のタイプのエラーと同じようにNullPointerExceptionが生じます。 最初にアプリケーションが動かなくてもがっかりしないで下さい。 このチュートリアルのすべてのステップを注意深くさかのぼって下さい。 もし、それでもアプリケーションが動くようにできなければ、Turbineのmailing listを有効に使って下さい。

Where to Go From Here

ここから進むべきところ

Congratulations! You have completed the Torque tutorial. Although this has only been an introduction to Torque, it should be sufficient to get you started with Torque in your applications. For those of you seeking additional information, there are several other documents on this site that can provide details on various subjects. Lastly, the source code is an invaluable resource when all else fails to provide answers!

おめでとうございます!あなたはTorqueチュートリアルを完了しました。 これはTorqueを紹介するだけのものですが、あなたのアプリケーションでTorqueを始めるには十分なものでしょう。 あなたたちの内の何人かは、さらなる情報を求めるでしょう。 このサイトには、いろいろな題目の詳細を提供するドキュメントがいくつかあります。 他のどれを参照しても答えを導いてくれないなら、最終的にはソースコードがかけがえのないリソースとなります。