チュートリアル
起動とH2コンソールの使用Settings of the H2 Console
JDBCを使用してデータベースに接続
新しいデータベースを作成する
サーバーを使用する
Hibernateを使用する
Using TopLink and Glassfish
Webアプリケーションで データベースを使用する
CSV (Comma Separated Values) サポート
アップグレード、 バックアップ、修復
Command Line Tools
OpenOffice Baseを使用する
Java Web Start / JNLP
Using a Connection Pool
フルテキストサーチ
User-Defined Variables
Date and Time
Using Spring
起動とH2コンソールの使用
The H2 Console application lets you access a SQL database using a browser interface. This can be a H2 database, or another database that supports the JDBC API.
これはクライアント / サーバーアプリケーションで、サーバーとクライアントの両方実行されることが必要です。
プラットフォームと環境によって、アプリケーションの起動方法が多数あります:
| OS | 起動 |
|---|---|
| Windows |
[スタート]、 [すべてのプログラム]、 [H2]、 [H2 Console]をクリックします When using the Sun JDK 1.5, a window with the title 'H2 Console ' should appear. When using the Sun JDK 1.6, an icon will be added to the system tray: ![]() If you don't get the window and the system tray icon, then maybe Java is not installed correctly (in this case, try another way to start the application). A browser window should open and point to the Login page at http://localhost:8082 . |
| Windows |
ファイルブラウザを開き、h2/binフォルダまで進み、h2.batをダブルクリックします。 正しく動作したら、システムトレイにアイコンが追加されます。 問題があれば、コンソールウィンドウにエラーメッセージが表示されます。 ブラウザウィンドウが開き、ログインページが表示されます。 (URL: http://localhost:8082/) |
| Any | Double click on the h2*.jar file. This only works if the .jar suffix is associated with java. |
| Any |
コンソールウィンドウを開き、'h2/lib'ディレクトリまで進み、下記を実行します: java -cp h2*.jar org.h2.tools.Server |
ファイアウォール
サーバーを起動させたら、ファイアウォールによるセキュリティ警告を受けるでしょう (1度インストールした場合)。外部ネットワークからあなたのマシンのデータベースにアクセスされたくないのであれば、ファイアーウォールが他の接続を遮断します。ローカルマシンからの接続はまだつながっています。他のコンピュータから、このコンピューターのデータベースにアクセスしたい場合のみ、 ファイアウォールでリモート接続を許可する必要があります。
It has been reported that when using Kaspersky 7.0 with firewall, the H2 Console is very slow when connecting over the IP address. A workaround is to connect using localhost, however this only works on the local machine.
小さなファイアーウォールはすでにサーバーに組み込まれています。 デフォルトによるこの構造は、他のコンピューターがサーバーにアクセスすることを許可していません。 これは、好きなように変更することができます (他のコンピューターからの接続を許可します)。
Javaをテストする
To find out which version of Java is installed, open a command prompt and type:
java -version
もしエラーメッセージが表示されたら、Javaのバイナリディレクトリを環境変数のPathに追加します。
Error Message 'Port may be in use'
You can only start one instance of the H2 Console, otherwise you will get the following error message: The Web server could not be started. Possible cause: another server is already running... . It is possible to start multiple console applications on the same computer (using different ports), but this is usually not required as the console supports multiple concurrent connections.
他のポートを使用する
もしポートが他のアプリケーションによって使用されている場合は、H2コンソールを異なったポートで起動したいはずです。これは、.h2.server.properties.ファイル内のポートを変更することにより実行できます。このファイルはユーザディレクトリ内に格納されています (Windowsでは通常、"Documents and Settings/<ユーザ名>")。関連する項目はwebPortです。
ブラウザを使用してサーバーに接続
If the server started successfully, you can connect to it using a web browser. JavaScript needs to be enabled. If you started the server on the same computer as the browser, open the URL http://localhost:8082 . If you want to connect to the application from another computer, you need to provide the IP address of the server, for example: http://192.168.0.2:8082 . If you enabled SSL on the server side, the URL needs to start with https:// .
複数の同時セッション
複数の同時ブラウザセッションがサポートされています。 データベースオブジェクトはサーバーに属しているため、同時接続の数はサーバーアプリケーションの利用可能メモリによって制限されています。
ログイン
ログインページでは、データベースに接続するための接続情報を設定する必要があります。 JDBCドライバをデータベースのクラスに設定し、JDBCのURL、ユーザ名とパスワードを入力します。 完了したら [Connect] をクリックします。
You can save and reuse previously saved settings. The settings are stored in a properties file (see Settings of the H2 Console ).
エラーメッセージ
エラーメッセージは赤で表示されます。 メッセージをクリックすることによって、例外の記録の表示、非表示を切り替えることができます。
データベースドライバの追加
Additional database drivers can be registered by adding the Jar file location of the driver to the environment variables H2DRIVERS or CLASSPATH. Example (Windows): to add the database driver library C:\Programs\hsqldb\lib\hsqldb.jar, set the environment variable H2DRIVERS to C:\Programs\hsqldb\lib\hsqldb.jar.
複数のドライバを設定することも可能です; それぞれのパスは ';' (Windows) や ':' (他のOS) で区切ります。 パス名内のスペースは有効です。設定は引用されません。
Using the H2 Console
The H2 Console application has three main panels: the toolbar on top, the tree on the left, and the query / result panel on the right. The database objects (for example, tables) are listed on the left panel. Type in a SQL command on the query panel and click 'Run'. The result of the command appears just below the command.
テーブル名、またはカラム名をインサートする
テーブル名やカラム名は、ツリー内のテーブル名、カラム名をクリックすることによってスクリプトにインサートすることができます。クエリが空の時にテーブルをクリックすると、 'SELECT * FROM ...' も同様に追加されます。 クエリを入力している間、使用されているテーブルはツリー内で自動的に拡張されます。例えば、 'SELECT * FROM TEST T WHERE T.' と入力すると、ツリー内のTESTテーブルは自動的に拡張されます。
切断とアプリケーションの終了
To log out of the database, click 'Disconnect' in the toolbar panel. However, the server is still running and ready to accept new sessions.
To stop the server, right click on the system tray icon and select [Exit]. If you don't have the system tray icon, navigate to [Preferences] and click [Shutdown], press [Ctrl]+[C] in the console where the server was started (Windows), or close the console window.
Settings of the H2 Console
The settings of the H2 Console are stored in a configuration file called .h2.server.properties in you user home directory. For Windows installations, the user home directory is usually C:\Documents and Settings\[username] . The configuration file contains the settings of the application and is automatically created when the H2 Console is first started.
JDBCを使用してデータベースに接続
To connect to a database, a Java application first needs to load the database driver, and then get a connection. A simple way to do that is using the following code:
import java.sql.*;
public class Test {
public static void main(String[] a)
throws Exception {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.
getConnection("jdbc:h2:~/test", "sa", "");
// add application code here
conn.close();
}
}
This code first loads the driver ( Class.forName(...) ) and then opens a connection (using DriverManager.getConnection() ). The driver name is "org.h2.Driver" . The database URL always needs to start with jdbc:h2: to be recognized by this database. The second parameter in the getConnection() call is the user name ('sa' for System Administrator in this example). The third parameter is the password. In this database, user names are not case sensitive, but passwords are.
新しいデータベースを作成する
初期設定では、データベースの指定されたURLがまだ存在しない場合、自動的に新しい (空の) データベースが作られます。
サーバーを使用する
H2 currently supports three server: a web server (for the H2 Console), a TCP server (for client/server connections) and an PG server (for PostgreSQL clients). The servers can be started in different ways, one is using the server tool.
Starting the Server Tool from Command Line
To start the server tool from the command line with the default settings, run:
java -cp h2*.jar org.h2.tools.Server
This will start the server tool with the default options. To get the list of options and default values, run:
java -cp h2*.jar org.h2.tools.Server -?
There are options available to use other ports, and start or not start parts. For details, see the API documentation of the server tool.
TCPサーバーに接続する
データベースへリモート接続するためには、TCPサーバーを使用します。次のドライバとデータベースURLを利用します:
- JDBCドライバクラス: org.h2.Driver
- データベースURL: jdbc:h2:tcp://localhost/~/test
データベースURLについての詳細は、特徴内のページをご覧下さい。
Starting the TCP Server within an Application
Servers can also be started and stopped from within an application. Sample code:
import org.h2.tools.Server; ... // start the TCP Server Server server = Server.createTcpServer(args).start(); ... // stop the TCP Server server.stop();
他の過程からTCPサーバーを終了する
The TCP server can be stopped from another process. To stop the server from the command line, run:
java org.h2.tools.Server -tcpShutdown tcp://localhost:9092
ユーザアプリケーションからサーバーを終了するには、次のコードを使用します:
org.h2.tools.Server.shutdownTcpServer("tcp://localhost:9094");
This function will only stop the TCP server. If other server were started in the same process, they will continue to run. To avoid recovery when the databases are opened the next time, all connections to the databases should be closed before calling this method. To stop a remote server, remote connections must be enabled on the server. Shutting down a TCP server can be protected using the option -tcpPassword (the same password must be used to start and stop the TCP server).
Hibernateを使用する
This database supports Hibernate version 3.1 and newer. You can use the HSQLDB Dialect, or the native H2 Dialect. Unfortunately the H2 Dialect included in Hibernate is buggy. A patch for Hibernate has been submitted. The dialect for the newest version of Hibernate is also available at src/tools/org/hibernate/dialect/H2Dialect.java.txt. You can rename it to H2Dialect.java and include this as a patch in your application.
Using TopLink and Glassfish
To use H2 with Glassfish (or Sun AS), set the Datasource Classname to org.h2.jdbcx.JdbcDataSource . You can set this in the GUI at Application Server - Resources - JDBC - Connection Pools, or by editing the file sun-resources.xml : at element jdbc-connection-pool , set the attribute datasource-classname to org.h2.jdbcx.JdbcDataSource .
The H2 database is compatible with HSQLDB and PostgreSQL. To take advantage of H2 specific features, use the H2Platform . The source code of this platform is included in H2 at src/tools/oracle/toplink/essentials/platform/database/DatabasePlatform.java.txt . You will need to copy this file to your application, and rename it to .java. To enable it, change the following setting in persistence.xml:
<property
name="toplink.target-database"
value="oracle.toplink.essentials.platform.database.H2Platform"/>
In old versions of Glassfish, the property name is toplink.platform.class.name .
Webアプリケーションで データベースを使用する
Webアプリケーション内からデータベースに接続するには様々な方法があります。 以下はTomcatかJBossを使用の場合のいくつかの例です。
エンベッドモード
(現在)最も簡単なソリューションはエンベッドモードでデータベースを使用することです。 それは、アプリケーションが起動する時や (良いソリューションは Servletリスナーを使用します。下記参照)、セッションが起動する時、アプリケーションにおける接続が開始するということを意味します。データベースは、セッションやアプリケーションが同じ過程で実行している限り、多様なセッションやアプリケーションから同時に接続されることが可能です。 多くのServletコンテナは (例; Tomcat) ただひとつのプロセスで利用されるので、問題はありません。 (Tomcatをクラスターモードで起動している場合を除いて)。 Tomcatはマルチスレッドとマルチクラスローダーを使用しています。もし複数のアプリケーションが同じデータベースに同時にアクセスする場合、データベースjarをshared/lib、またはserver/libディレクトリに置く必要があります。 webアプリケーションが起動した時にデータベースを開き、webアプリケーションが終了した時にデータベースを閉じるのが良い方法です。もし複数のアプリケーションを使用する場合、そのうちひとつのアプリケーションをこのように動作することが必要です。アプリケーションでは、セッションごとにひとつの接続を使うか、リクエスト(アクション)ごとにひとつの接続を使うという概念があります。これらの接続はできる限り、使用後に終了させます(しかし、終了させなくても悪くはありません)。
サーバーモード
サーバーモードは類似していますが、他のプロセスでサーバーを起動させることを許可しています。
データベースの起動と終了にServletリスナーを使用する
Add the h2*.jar file to your web application, and add the following snippet to your web.xml file (between the 'context-param' and the 'filter' section):
<listener>
<listener-class>org.h2.server.web.DbStarter</listener-class>
</listener>
For details on how to access the database, see the file DbStarter.java. By default the DbStarter listener opens an embedded connection using the database URL 'jdbc:h2:~/test', user name 'sa', and password 'sa'. If you want to use this connection within your servlet, you can access as follows:
Connection conn = getServletContext().getAttribute("connection");
The DbStarter can also start the TCP server, however this is disabled by default. To enable it, use the parameter db.tcpServer in the file web.xml. Here is the complete list of options. These options need to be placed between the 'description' tag and the 'listener' / 'filter' tags:
<context-param>
<param-name>db.url</param-name>
<param-value>jdbc:h2:~/test</param-value>
</context-param>
<context-param>
<param-name>db.user</param-name>
<param-value>sa</param-value>
</context-param>
<context-param>
<param-name>db.password</param-name>
<param-value>sa</param-value>
</context-param>
<context-param>
<param-name>db.tcpServer</param-name>
<param-value>-tcpAllowOthers</param-value>
</context-param>
When the web application is stopped, the database connection will be closed automatically. If the TCP server is started within the DbStarter, it will also be stopped automatically.
Using the H2 Console Servlet
The H2 Console is a standalone application and includes its own web server, but it can be used as a servlet as well. To do that, include the the h2 jar file in your application, and add the following configuration to your web.xml:
<servlet>
<servlet-name>H2Console</servlet-name>
<servlet-class>org.h2.server.web.WebServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>H2Console</servlet-name>
<url-pattern>/console/*</url-pattern>
</servlet-mapping>
For details, see also src/tools/WEB-INF/web.xml .
To create a web application with just the H2 Console, run the following command:
build warConsole
CSV (Comma Separated Values) サポート
The CSV file support can be used inside the database using the functions CSVREAD and CSVWRITE, or it can be used outside the database as a standalone tool.
データベース内からCSVファイルに書き込む
クエリからCSVファイルを作成するのに、組込み関数 CSVWRITEを使用することができます。例:
CREATE TABLE TEST(ID INT, NAME VARCHAR);
INSERT INTO TEST VALUES(1, 'Hello'), (2, 'World');
CALL CSVWRITE('test.csv', 'SELECT * FROM TEST');
データベース内からCSVファイルを読み込む
CSVREAD関数を使用してCSVファイルを読み込むことができます。 例:
SELECT * FROM CSVREAD('test.csv');
JavaアプリケーションからCSVファイルに書き込む
データベースを全く使用しなくても、JavaアプリケーションでCSVツールを使用することができます。 例:
import java.sql.*;
import org.h2.tools.Csv;
import org.h2.tools.SimpleResultSet;
public class TestCsv {
public static void main(String[] args) throws Exception {
SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("NAME", Types.VARCHAR, 255, 0);
rs.addColumn("EMAIL", Types.VARCHAR, 255, 0);
rs.addRow("Bob Meier", "bob.meier@abcde.abc");
rs.addRow("John Jones", "john.jones@abcde.abc");
Csv.getInstance().write("data/test.csv", rs, null);
}
}
JavaアプリケーションからCSVファイルを読み込む
データベースを開かなくてもCSVファイルを読み込むことができます。 例:
import java.sql.*;
import org.h2.tools.Csv;
public class TestCsv {
public static void main(String[] args) throws Exception {
ResultSet rs = Csv.getInstance().
read("data/test.csv", null, null);
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
for (int i = 0; i < meta.getColumnCount(); i++) {
System.out.println(
meta.getColumnLabel(i + 1) + ": " +
rs.getString(i + 1));
}
System.out.println();
}
rs.close();
}
}
アップグレード、 バックアップ、修復
データベースのアップグレー
あるバージョンのデータベースエンジンを次のバージョンにアップグレードする際の推奨する方法は、 古いエンジンを使って(SQLスクリプトのフォームでの)データベースのバックアップを作成し、新しいエンジンを使ってSQLスクリプトを実行します。
バックアップ
異なった方法のデータベースのバックアップがあります。例えば、データベースファイルをコピーすることが可能です。しかしながら、この方法はデータベースが使用されている間は推奨しません。データベースは人が判読しやすく、極めて大きいというわけではありません。データベースバックアップの推奨する方法は、圧縮したSQLスクリプトを作成することです。この方法は、バックアップツールを使用することで可能です:
java org.h2.tools.Script -url jdbc:h2:~/test -user sa -script test.zip -options compression zip
オプションについての情報は、SQLコマンドスクリプトをご覧下さい。バックアップは遠隔で行えますが、ファイルはサーバー側に作られます。サーバーからファイルを取るのに、ビルトインFTPサーバーを使用することができます。データベースのバックアップを作るのに、SQLコマンドスクリプトを 使用することもできます。
修復
SQLスクリプトファイルからデータベースを修復するには、RunScriptツールを使用する必要があります:
java org.h2.tools.RunScript -url jdbc:h2:~/test -user sa -script test.zip -options compression zip
オプションについての情報は、SQLコマンド RUNSCRIPTをご覧下さい。修復は遠隔で行えますが、サーバー側にファイルが存在する必要があります。サーバーからファイルをコピーするのに、ビルトインFTPサーバーを使用することができます。SQLスクリプトを実行するために、 SQLコマンド RUNSCRIPTを使用することができます。SQLスクリプトファイルには、RUNSCRIPTコマンドのフォーム内に他のスクリプトファイルのリファレンスが含まれています。しかしながら、サーバーモードを使用している時、リファレンススクリプトファイルはサーバー側で利用可能であることが必要です。
オンラインバックアップ
BACKUP SQLステートメントとバックアップツールの両方が全てのデータベースファイルをzipファイル形式で作成します。しかし、このファイルのコンテンツは人間が解読可能なものではありません。SCRIPTステートメントを除いて、BACKUPステートメントはデータベースオブジェクトをロックしないため、他のユーザーをブロックしません。結果として、バックアップは一貫性のあるトランザクションです:
BACKUP TO 'backup.zip'
バックアップツール (org.h2.tools.Backup) はオンラインバックアップを作成するために利用されません; このプログラムが実行されている間、データベースは使用されてはいけません。
Creating a backup while the database is running is not supported, except if the file systems support creating snapshots. The problem is that it can't be guaranteed that the data is copied in the right order.
Command Line Tools
This database comes with a number of command line tools. To get more information about a tool, start it with the parameter '-?', for example:
java -cp h2*.jar org.h2.tools.Backup -?
The command line tools are:
- バックアップ creates a backup of a database.
- ChangeFileEncryption allows changing the file encryption password or algorithm of a database.
- Console starts the browser based H2 Console.
- ConvertTraceFile converts a .trace.db file to a Java application and SQL script.
- CreateCluster creates a cluster from a standalone database.
- DeleteDbFiles deletes all files belonging to a database.
- Recover helps recovering a corrupted database.
- Restore restores a backup of a database.
- RunScript runs a SQL script against a database.
- Script allows converting a database to a SQL script for backup or migration.
- Server is used in the server mode to start a H2 server.
- Shell is a command line database tool.
The tools can also be called from an application by calling the main or another public method. For details, see the Javadoc documentation.
OpenOffice Baseを使用する
OpenOffice.org Base はJDBC API上のデータベースアクセスをサポートしています。 OpenOffice Baseを使ってH2データベースに接続するためには、最初にOpenOfficeにJDBCドライバを追加する必要があります。H2データベースに接続する手順:
- Start OpenOffice Writer, go to [Tools], [Options]
- Make sure you have selected a Java runtime environment in OpenOffice.org / Java
- Click [Class Path...], [Add Archive...]
- Select your h2 jar file (location is up to you, could be wherever you choose)
- Click [OK] (as much as needed), stop OpenOffice (including the Quickstarter)
- OpenOffice Base を起動する
- Connect to an existing database; select [JDBC]; [Next]
- Example datasource URL: jdbc:h2:~/test
- JDBCドライバクラス: org.h2.Driver
Now you can access the database stored in the current users home directory.
To use H2 in NeoOffice (OpenOffice without X11):
- In NeoOffice, go to [NeoOffice], [Preferences]
- Look for the page under [NeoOffice], [Java]
- Click [Class Path], [Add Archive...]
- Select your h2 jar file (location is up to you, could be wherever you choose)
- Click [OK] (as much as needed), restart NeoOffice.
Now, when creating a new database using the "Database Wizard" :
- Click [File], [New], [Database].
- Select [Connect to existing database] and the select [JDBC]. Click next.
- Example datasource URL: jdbc:h2:~/test
- JDBCドライバクラス: org.h2.Driver
Another solution to use H2 in NeoOffice is:
- Package the h2 jar within an extension package
- Install it as a Java extension in NeoOffice
This can be done by create it using the NetBeans OpenOffice plugin. See also Extensions Development .
Java Web Start / JNLP
Java Web Start / JNLP (Java Network Launch Protocol) を使用している時、パーミッションタグは.jnlp ファイルに設定され、application.jarファイルは署名されていなければなりません。そうでなければ、ファイルシステムに書き込もうとした時、次の例外が発生するでしょう: java.security.AccessControlException: access denied (java.io.FilePermission ... read) パーミッションタグの例:
<security>
<all-permissions/>
</security>
Using a Connection Pool
For H2, opening a connection is fast if the database is already open. Still, using a connection pool improves performance if you open and close connections a lot. A simple connection pool is included in H2. It is based on the Mini Connection Pool Manager from Christian d'Heureuse. There are other, more complex, open source connection pools available, for example the Apache Commons DBCP . For H2, it is about twice as faster to get a connection from the built-in connection pool than to get one using DriverManager.getConnection(). The build-in connection pool is used as follows:
import java.sql.*;
import org.h2.jdbcx.JdbcConnectionPool;
public class Test {
public static void main(String[] args) throws Exception {
JdbcConnectionPool cp = JdbcConnectionPool.create(
"jdbc:h2:~/test", "sa", "sa");
for (int i = 0; i < args.length; i++) {
Connection conn = cp.getConnection();
conn.createStatement().execute(args[i]);
conn.close();
}
cp.dispose();
}
}
フルテキストサーチ
H2 includes two fulltext search implementations. One is using Apache Lucene, and the other (the native implementation) stores the index data in special tables in the database.
Using the Native Fulltext Search
初期化するには、次を呼び出します:
CREATE ALIAS IF NOT EXISTS FT_INIT FOR "org.h2.fulltext.FullText.init"; CALL FT_INIT();
You need to initialize it in each database where you want to use it. Afterwards, you can create a fulltext index for a table using:
CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR);
INSERT INTO TEST VALUES(1, 'Hello World');
CALL FT_CREATE_INDEX('PUBLIC', 'TEST', NULL);
PUBLIC is the schema, TEST is the table name. The list of column names (column separated) is optional, in this case all columns are indexed. The index is updated in realtime. To search the index, use the following query:
SELECT * FROM FT_SEARCH('Hello', 0, 0);
This will produce a result set that contains the query needed to retrieve the data:
QUERY: "PUBLIC"."TEST" WHERE "ID"=1
To get the raw data, use FT_SEARCH_DATA('Hello', 0, 0); . The result contains the columns SCHEMA (the schema name), TABLE (the table name), COLUMNS (an array of column names), and KEYS (an array of objects). To join a table, use a join as in: SELECT T.* FROM FT_SEARCH_DATA('Hello', 0, 0) FT, TEST T WHERE FT.TABLE='TEST' AND T.ID= FT.KEYS[0];
Javaアプリケーション内からインデックスを呼び出すことも可能です:
org.h2.fulltext.FullText.search(conn, text, limit, offset); org.h2.fulltext.FullText.searchData(conn, text, limit, offset);
Luceneフルテキストサーチを使用する
To use the Lucene full text search, you need the Lucene library in the classpath. How to do that depends on the application; if you use the H2 Console, you can add the Lucene jar file to the environment variables H2DRIVERS or CLASSPATH. To initialize the Lucene fulltext search in a database, call:
CREATE ALIAS IF NOT EXISTS FTL_INIT FOR "org.h2.fulltext.FullTextLucene.init"; CALL FTL_INIT();
You need to initialize it in each database where you want to use it. Afterwards, you can create a full text index for a table using:
CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR);
INSERT INTO TEST VALUES(1, 'Hello World');
CALL FTL_CREATE_INDEX('PUBLIC', 'TEST', NULL);
PUBLIC is the schema, TEST is the table name. The list of column names (column separated) is optional, in this case all columns are indexed. The index is updated in realtime. To search the index, use the following query:
SELECT * FROM FTL_SEARCH('Hello', 0, 0);
This will produce a result set that contains the query needed to retrieve the data:
QUERY: "PUBLIC"."TEST" WHERE "ID"=1
To get the raw data, use FTL_SEARCH_DATA('Hello', 0, 0); . The result contains the columns SCHEMA (the schema name), TABLE (the table name), COLUMNS (an array of column names), and KEYS (an array of objects). To join a table, use a join as in: SELECT T.* FROM FTL_SEARCH_DATA('Hello', 0, 0) FT, TEST T WHERE FT.TABLE='TEST' AND T.ID= FT.KEYS[0];
Javaアプリケーション内からインデックスを呼び出すことも可能です:
org.h2.fulltext.FullTextLucene.search(conn, text, limit, offset); org.h2.fulltext.FullTextLucene.searchData(conn, text, limit, offset);
User-Defined Variables
This database supports user-defined variables. Variables start with @ and can be used wherever expressions or parameters are allowed. Variables are not persisted and session scoped, that means only visible from within the session in which they are defined. A value is usually assigned using the SET command:
SET @USER = 'Joe';
The value can also be changed using the SET() method. This is useful in queries:
SET @TOTAL = NULL; SELECT X, SET(@TOTAL, IFNULL(@TOTAL, 1.) * X) F FROM SYSTEM_RANGE(1, 50);
Variables that are not set evaluate to NULL. The data type of a user-defined variable is the data type of the value assigned to it, that means it is not necessary (or possible) to declare variable names before using them. There are no restrictions on the assigned values; large objects (LOBs) are supported as well.
Date and Time
Date, time and timestamp values support ISO 8601 formatting, including time zone:
CALL TIMESTAMP '2008-01-01 12:00:00+01:00';
If the time zone is not set, the value is parsed using the current time zone setting of the system. Date and time information is stored in H2 database files in GMT (Greenwich Mean Time). If the database is opened using another system time zone, the date and time will change accordingly. If you want to move a database from one time zone to the other and don't want this to happen, you need to create a SQL script file using the SCRIPT command or Script tool, and then load the database using the RUNSCRIPT command or the RunScript tool in the new time zone.
Using Spring
Use the following configuration to start and stop the H2 TCP server using the Spring Framework:
<bean id="org.h2.tools.Server"
class="org.h2.tools.Server"
factory-method="createTcpServer"
init-method="start"
destroy-method="stop">
<constructor-arg value="-tcp,-tcpAllowOthers,true,-tcpPort,8043" />
</bean>
The "destroy-method" will help prevent exceptions on hot-redeployment or when restarting the server.
![[H2 icon]](images/db-16.png)