クライアント側のリソース要件の削減

The Advanced Server JDBC driver retrieves the results of a SQL query as a ResultSet object. If a query returns a large number of rows, using a batched ResultSet will:

  • 最初の行を取得するのにかかる時間を短縮します。

  • 必要な行のみを取得して時間を節約します。

  • クライアントのメモリ要件を減らします。

When you reduce the fetch size of a ResultSet object, the driver doesn’t copy the entire ResultSet across the network (from the server to the client). Instead, the driver requests a small number of rows at a time; as the client application moves through the result set, the driver fetches the next batch of rows from the server.

バッチ結果セットは、すべての状況で使用できるわけではありません。以下の制限を守らないと、ドライバーは静かに ResultSet 全体を一度にフェッチします:

  • クライアントアプリケーションは autocommit を無効にする必要があります。

  • The Statement object must be created with a ResultSet type of TYPE_FORWARD_ONLY type (which is the default). TYPE_FORWARD_ONLY result sets can only step forward through the ResultSet.

  • クエリは、単一のSQLステートメントで構成する必要があります。

ステートメントオブジェクトのバッチサイズの変更

ResultSet オブジェクトのバッチサイズを制限すると、データの取得が高速化され、クライアント側アプリケーションに必要なリソースが削減されます。リスト1.5では、バッチサイズが5行に制限された Statement オブジェクトを作成します。

// Make sure autocommit is off
conn.setAutoCommit(false);

Statement stmt = conn.createStatement();
// Set the Batch Size.
stmt.setFetchSize(5);

ResultSet rs = stmt.executeQuery("SELECT * FROM emp");
while (rs.next())
  System.out.println("a row was returned.");

rs.close();
stmt.close();

conn.setAutoCommit(false) を呼び出すと、最初の行を取得する前にサーバーが ResultSet を閉じないことが保証されます。 Connection を準備した後、 Statement オブジェクトを構築できます:

Statement stmt = db.createStatement();

次のコードは、クエリを実行する前にバッチサイズを5(行)に設定します。

stmt.setFetchSize(5);

ResultSet rs = stmt.executeQuery("SELECT * FROM emp");

ResultSet オブジェクトの各行に対して、 println() の呼び出しは a row was returned を出力します。

System.out.println("a row was returned.");

ResultSet にはテーブル内のすべての行が含まれていますが、サーバーから一度に5行しかフェッチされないことに注意してください。クライアントの観点から見ると、 batched の結果セットと unbatched の結果セットの唯一の違いは、バッチ処理された結果がより短い時間で最初の行を返す可能性があることです。

次に、特定のJDBCアプリケーションのパフォーマンスを向上させるために使用できる別の機能( the PreparedStatement )を見ていきます。