Debian Codegraph @

src/docsrc/html/tutorial.html

raw
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2 <!--
3 Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
4 and the EPL 1.0 (https://h2database.com/html/license.html).
5 Initial Developer: H2 Group
6 -->
7 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
8 <head>
9 <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
10 <meta name="viewport" content="width=device-width, initial-scale=1" />
11 <title>
12 Tutorial
13 </title>
14 <link rel="stylesheet" type="text/css" href="stylesheet.css" />
15 <!-- [search] { -->
16 <script type="text/javascript" src="navigation.js"></script>
17 </head><body onload="frameMe();">
18 <table class="content"><tr class="content"><td class="content"><div class="contentDiv">
19 <!-- } -->
20
21 <h1 id="tutorial_index">Tutorial</h1>
22 <a href="#tutorial_starting_h2_console">
23 Starting and Using the H2 Console</a><br />
24 <a href="#console_syntax">
25 Special H2 Console Syntax</a><br />
26 <a href="#console_settings">
27 Settings of the H2 Console</a><br />
28 <a href="#connecting_using_jdbc">
29 Connecting to a Database using JDBC</a><br />
30 <a href="#creating_new_databases">
31 Creating New Databases</a><br />
32 <a href="#using_server">
33 Using the Server</a><br />
34 <a href="#using_hibernate">
35 Using Hibernate</a><br />
36 <a href="#using_toplink">
37 Using TopLink and Glassfish</a><br />
38 <a href="#using_eclipselink">
39 Using EclipseLink</a><br />
40 <a href="#using_activemq">
41 Using Apache ActiveMQ</a><br />
42 <a href="#using_netbeans">
43 Using H2 within NetBeans</a><br />
44 <a href="#using_jooq">
45 Using H2 with jOOQ</a><br />
46 <a href="#web_applications">
47 Using Databases in Web Applications</a><br />
48 <a href="#csv">
49 CSV (Comma Separated Values) Support</a><br />
50 <a href="#upgrade_backup_restore">
51 Upgrade, Backup, and Restore</a><br />
52 <a href="#command_line_tools">
53 Command Line Tools</a><br />
54 <a href="#shell_tool">
55 The Shell Tool</a><br />
56 <a href="#open_office">
57 Using OpenOffice Base</a><br />
58 <a href="#web_start">
59 Java Web Start / JNLP</a><br />
60 <a href="#connection_pool">
61 Using a Connection Pool</a><br />
62 <a href="#fulltext">
63 Fulltext Search</a><br />
64 <a href="#user_defined_variables">
65 User-Defined Variables</a><br />
66 <a href="#date_time">
67 Date and Time</a><br />
68 <a href="#spring">
69 Using Spring</a><br />
70 <a href="#osgi">
71 OSGi</a><br />
72 <a href="#jmx">
73 Java Management Extension (JMX)</a><br />
74
75 <h2 id="tutorial_starting_h2_console">Starting and Using the H2 Console</h2>
76 <p>
77 The H2 Console application lets you access a database using a browser.
78 This can be a H2 database, or another database that supports the JDBC API.
79 </p>
80 <img src="images/console-2.png"
81 width="535" height="179"
82 alt="Web Browser - H2 Console Server - H2 Database" />
83 <p>
84 This is a client/server application, so both a server and a client (a browser) are required to run it.
85 </p><p>
86 Depending on your platform and environment, there are multiple ways to start the H2 Console:
87 </p>
88 <table class="main">
89 <tr><th>OS</th><th>Start</th></tr>
90 <tr>
91 <td>Windows</td>
92 <td>
93 Click [Start], [All Programs], [H2], and [H2 Console (Command Line)]<br />
94 An icon will be added to the system tray:
95 <img src="images/db-64-t.png"
96 width="32" height="32"
97 alt="H2 database icon" /><br />
98 If you don't get the window and the system tray icon,
99 then maybe Java is not installed correctly (in this case, try another way to start the application).
100 A browser window should open and point to the login page at <code>http://localhost:8082</code>.
101 </td>
102 </tr>
103 <tr>
104 <td>Windows</td>
105 <td>
106 Open a file browser, navigate to <code>h2/bin</code>, and
107 double click on <code>h2.bat</code>.<br />
108 A console window appears. If there is a problem, you will see an error message
109 in this window. A browser window will open and point to the login page
110 (URL: <code>http://localhost:8082</code>).
111 </td>
112 </tr>
113 <tr>
114 <td>Any</td>
115 <td>
116 Double click on the <code>h2*.jar</code> file.
117 This only works if the <code>.jar</code> suffix is associated with Java.
118 </td>
119 </tr>
120 <tr>
121 <td>Any</td>
122 <td>
123 Open a console window, navigate to the directory <code>h2/bin</code>, and type:
124 <pre>java -jar h2*.jar</pre>
125 </td>
126 </tr>
127 </table>
128 <p>
129 If the console startup procedure is unable to locate the default system web browser,
130 an error message may be displayed. It is possible to explicitly tell H2 which
131 program/script to use when opening a system web browser by setting either the BROWSER
132 environment variable, or the h2.browser java property.
133 </p>
134
135 <h3>Firewall</h3>
136 <p>
137 If you start the server, you may get a security warning from the firewall (if you have installed one).
138 If you don't want other computers in the network to access the application on your machine, you can
139 let the firewall block those connections. The connection from the local machine will still work.
140 Only if you want other computers to access the database on this computer, you need allow remote connections
141 in the firewall.
142 </p>
143 <p>
144 It has been reported that when using Kaspersky 7.0 with firewall, the H2 Console is very slow when
145 connecting over the IP address. A workaround is to connect using 'localhost'.
146 </p>
147 <p>
148 A small firewall is already built into the server: other computers may not connect to the server by default.
149 To change this, go to 'Preferences' and select 'Allow connections from other computers'.
150 </p>
151
152 <h3>Testing Java</h3>
153 <p>
154 To find out which version of Java is installed, open a command prompt and type:
155 </p>
156 <pre>
157 java -version
158 </pre>
159 <p>
160 If you get an error message, you may need to add the Java binary directory to the path environment variable.
161 </p>
162
163 <h3>Error Message 'Port may be in use'</h3>
164 <p>
165 You can only start one instance of the H2 Console,
166 otherwise you will get the following error message:
167 "The Web server could not be started. Possible cause: another server is already running...".
168 It is possible to start multiple console applications on the same computer (using different ports),
169 but this is usually not required as the console supports multiple concurrent connections.
170 </p>
171
172 <h3>Using another Port</h3>
173 <p>
174 If the default port of the H2 Console is already in use by another application,
175 then a different port needs to be configured. The settings are stored in a properties file.
176 For details, see <a href="#console_settings">Settings of the H2 Console</a>.
177 The relevant entry is <code>webPort</code>.
178 </p>
179 <p>
180 If no port is specified for the TCP and PG servers, each service will try to listen on its default port.
181 If the default port is already in use, a random port is used.
182 </p>
183
184 <h3>Connecting to the Server using a Browser</h3>
185 <p>
186 If the server started successfully, you can connect to it using a web browser.
187 Javascript needs to be enabled.
188 If you started the server on the same computer as the browser, open the URL <code>http://localhost:8082</code>.
189 If you want to connect to the application from another computer, you need to provide the IP address of the server, for example:
190 <code>http://192.168.0.2:8082</code>.
191 If you enabled TLS on the server side, the URL needs to start with <code>https://</code>.
192 </p>
193
194 <h3>Multiple Concurrent Sessions</h3>
195 <p>
196 Multiple concurrent browser sessions are supported. As that the database objects reside on the server,
197 the amount of concurrent work is limited by the memory available to the server application.
198 </p>
199
200 <h3>Login</h3>
201 <p>
202 At the login page, you need to provide connection information to connect to a database.
203 Set the JDBC driver class of your database, the JDBC URL, user name, and password.
204 If you are done, click [Connect].
205 </p><p>
206 You can save and reuse previously saved settings. The settings are stored in a properties file
207 (see <a href="#console_settings">Settings of the H2 Console</a>).
208 </p>
209
210 <h3>Error Messages</h3>
211 <p>
212 Error messages in are shown in red. You can show/hide the stack trace of the exception
213 by clicking on the message.
214 </p>
215
216 <h3>Adding Database Drivers</h3>
217 <p>
218 To register additional JDBC drivers (MySQL, PostgreSQL, HSQLDB,...),
219 add the jar file names to the environment variables <code>H2DRIVERS</code> or <code>CLASSPATH</code>.
220 Example (Windows): to add the HSQLDB JDBC driver
221 <code>C:\Programs\hsqldb\lib\hsqldb.jar</code>, set the environment variable
222 <code>H2DRIVERS</code> to
223 <code>C:\Programs\hsqldb\lib\hsqldb.jar</code>.
224 </p><p>
225 Multiple drivers can be set; entries need to be separated by <code>;</code> (Windows)
226 or <code>:</code> (other operating systems).
227 Spaces in the path names are supported. The settings must not be quoted.
228 </p>
229
230 <h3>Using the H2 Console</h3>
231 <p>
232 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.
233 The database objects (for example, tables) are listed on the left.
234 Type a SQL command in the query panel and click [Run]. The result appears just below the command.
235 </p>
236
237 <h3>Inserting Table Names or Column Names</h3>
238 <p>
239 To insert table and column names into the script, click on the item in the tree.
240 If you click on a table while the query is empty, then <code>SELECT * FROM ...</code> is added.
241 While typing a query, the table that was used is expanded in the tree.
242 For example if you type <code>SELECT * FROM TEST T WHERE T.</code> then the table TEST is expanded.
243 </p>
244
245 <h3>Disconnecting and Stopping the Application</h3>
246 <p>
247 To log out of the database, click [Disconnect] in the toolbar panel.
248 However, the server is still running and ready to accept new sessions.
249 </p><p>
250 To stop the server, right click on the system tray icon and select [Exit].
251 If you don't have the system tray icon,
252 navigate to [Preferences] and click [Shutdown],
253 press [Ctrl]+[C] in the console where the server was started (Windows),
254 or close the console window.
255 </p>
256
257 <h2 id="console_syntax">Special H2 Console Syntax</h2>
258 <p>
259 The H2 Console supports a few built-in commands.
260 Those are interpreted within the H2 Console, so they work with any database.
261 Built-in commands need to be at the beginning of a statement (before any remarks),
262 otherwise they are not parsed correctly. If in doubt, add <code>;</code> before the command.
263 </p>
264 <table class="main">
265 <tr>
266 <th>Command(s)</th>
267 <th>Description</th>
268 </tr>
269 <tr>
270 <td class="notranslate">
271 @autocommit_true;<br />
272 @autocommit_false;
273 </td>
274 <td>
275 Enable or disable autocommit.
276 </td>
277 </tr>
278 <tr>
279 <td class="notranslate">
280 @cancel;
281 </td>
282 <td>
283 Cancel the currently running statement.
284 </td>
285 </tr>
286 <tr>
287 <td class="notranslate">
288 @columns null null TEST;<br />
289 @index_info&nbsp;null&nbsp;null&nbsp;TEST;<br />
290 @tables;<br />
291 @tables null null TEST;<br />
292 </td>
293 <td>
294 Call the corresponding <code>DatabaseMetaData.get</code> method.
295 Patterns are case sensitive (usually identifiers are uppercase).
296 For information about the parameters, see the Javadoc documentation.
297 Missing parameters at the end of the line are set to null. The complete list of metadata commands is:
298 <code>
299 @attributes, @best_row_identifier, @catalogs, @columns,
300 @column_privileges, @cross_references, @exported_keys,
301 @imported_keys, @index_info, @primary_keys, @procedures,
302 @procedure_columns, @pseudo_columns, @schemas, @super_tables, @super_types,
303 @tables, @table_privileges, @table_types, @type_info, @udts,
304 @version_columns
305 </code>
306 </td>
307 </tr>
308 <tr>
309 <td class="notranslate">
310 @edit select * from test;
311 </td>
312 <td>
313 Use an updatable result set.
314 </td>
315 </tr>
316 <tr>
317 <td class="notranslate">
318 @generated&nbsp;insert&nbsp;into&nbsp;test()&nbsp;values();<br />
319 @generated(1)&nbsp;insert&nbsp;into&nbsp;test()&nbsp;values();<br />
320 @generated(ID, "TIMESTAMP")&nbsp;insert&nbsp;into&nbsp;test()&nbsp;values();
321 </td>
322 <td>
323 Show the result of <code>Statement.getGeneratedKeys()</code>.
324 Names or one-based indexes of required columns can be optionally specified.
325 </td>
326 </tr>
327 <tr>
328 <td class="notranslate">
329 @history;
330 </td>
331 <td>
332 List the command history.
333 </td>
334 </tr>
335 <tr>
336 <td class="notranslate">
337 @info;
338 </td>
339 <td>
340 Display the result of various <code>Connection</code> and <code>DatabaseMetaData</code> methods.
341 </td>
342 </tr>
343 <tr>
344 <td class="notranslate">
345 @list select * from test;
346 </td>
347 <td>
348 Show the result set in list format (each column on its own line, with row numbers).
349 </td>
350 </tr>
351 <tr>
352 <td class="notranslate">
353 @loop 1000 select ?, ?/*rnd*/;<br />
354 @loop 1000 @statement select ?;
355 </td>
356 <td>
357 Run the statement this many times.
358 Parameters (<code>?</code>) are set using a loop from 0 up to x - 1.
359 Random values are used for each <code>?/*rnd*/</code>.
360 A Statement object is used instead of a PreparedStatement if <code>@statement</code> is used.
361 Result sets are read until <code>ResultSet.next()</code> returns <code>false</code>.
362 Timing information is printed.
363 </td>
364 </tr>
365 <tr>
366 <td class="notranslate">
367 @maxrows&nbsp;20;
368 </td>
369 <td>
370 Set the maximum number of rows to display.
371 </td>
372 </tr>
373 <tr>
374 <td class="notranslate">
375 @memory;
376 </td>
377 <td>
378 Show the used and free memory. This will call <code>System.gc()</code>.
379 </td>
380 </tr>
381 <tr>
382 <td class="notranslate">
383 @meta&nbsp;select&nbsp;1;
384 </td>
385 <td>
386 List the <code>ResultSetMetaData</code> after running the query.
387 </td>
388 </tr>
389 <tr>
390 <td class="notranslate">
391 @parameter_meta&nbsp;select&nbsp;?;
392 </td>
393 <td>
394 Show the result of the <code>PreparedStatement.getParameterMetaData()</code> calls.
395 The statement is not executed.
396 </td>
397 </tr>
398 <tr>
399 <td class="notranslate">
400 @prof_start;<br />
401 call&nbsp;hash('SHA256',&nbsp;'',&nbsp;1000000);<br />
402 @prof_stop;
403 </td>
404 <td>
405 Start/stop the built-in profiling tool.
406 The top 3 stack traces of the statement(s) between start and stop are listed
407 (if there are 3).
408 </td>
409 </tr>
410 <tr>
411 <td class="notranslate">
412 @prof_start;<br />
413 @sleep 10;<br />
414 @prof_stop;
415 </td>
416 <td>
417 Sleep for a number of seconds. Used to profile a long running query or
418 operation that is running in another session (but in the same process).
419 </td>
420 </tr>
421 <tr>
422 <td class="notranslate">
423 @transaction_isolation;<br />
424 @transaction_isolation&nbsp;2;
425 </td>
426 <td>
427 Display (without parameters) or change
428 (with parameters 1, 2, 4, 8) the transaction isolation level.
429 </td>
430 </tr>
431 </table>
432
433 <h2 id="console_settings">Settings of the H2 Console</h2>
434 <p>
435 The settings of the H2 Console are stored in a configuration file
436 called <code>.h2.server.properties</code> in you user home directory.
437 For Windows installations, the user home directory is usually
438 <code>C:\Documents and Settings\[username]</code> or
439 <code>C:\Users\[username]</code>.
440 The configuration file contains the settings of the application and is automatically created when the H2 Console is first started.
441 Supported settings are:
442 </p>
443 <ul><li><code>webAllowOthers</code>: allow other computers to connect.
444 </li><li><code>webPort</code>: the port of the H2 Console
445 </li><li><code>webSSL</code>: use encrypted TLS (HTTPS) connections.
446 </li><li><code>webAdminPassword</code>: hash of password to access preferences and tools of H2 Console,
447 use <code>org.h2.server.web.WebServer.encodeAdminPassword(String)</code> to generate a hash for your password.
448 Always use long complex passwords, especially when access from other hosts is enabled.
449 </li></ul>
450 <p>
451 In addition to those settings, the properties of the last recently used connection
452 are listed in the form
453 <code>&lt;number&gt;=&lt;name&gt;|&lt;driver&gt;|&lt;url&gt;|&lt;user&gt;</code>
454 using the escape character <code>\</code>.
455 Example:
456 <code>1=Generic H2 (Embedded)|org.h2.Driver|jdbc\:h2\:~/test|sa</code>
457 </p>
458
459 <h2 id="connecting_using_jdbc">Connecting to a Database using JDBC</h2>
460 <p>
461 To connect to a database, a Java application first needs to load the database driver,
462 and then get a connection. A simple way to do that is using the following code:
463 </p>
464 <pre>
465 import java.sql.*;
466 public class Test {
467 public static void main(String[] a)
468 throws Exception {
469 Connection conn = DriverManager.
470 getConnection("jdbc:h2:~/test", "sa", "");
471 // add application code here
472 conn.close();
473 }
474 }
475 </pre>
476 <p>
477 This code opens a connection (using <code>DriverManager.getConnection()</code>).
478 The driver name is <code>"org.h2.Driver"</code>.
479 The database URL always needs to start with <code>jdbc:h2:</code>
480 to be recognized by this database. The second parameter in the <code>getConnection()</code> call
481 is the user name (<code>sa</code> for System Administrator in this example). The third parameter is the password.
482 In this database, user names are not case sensitive, but passwords are.
483 </p>
484
485 <h2 id="creating_new_databases">Creating New Databases</h2>
486 <p>
487 By default, if the database specified in the <a href="features.html#database_url">embedded</a> URL does not yet exist,
488 a new (empty) database is created automatically.
489 The user that created the database automatically becomes the administrator of this database.
490 </p>
491 <p>
492 Auto-creation of databases can be disabled, see
493 <a href="features.html#database_only_if_exists">Opening a Database Only if it Already Exists</a>.
494 </p>
495 <p>
496 H2 Console does not allow creation of databases unless a browser window is opened by Console during its
497 startup or from its icon in the system tray and remote access is not enabled.
498 A context menu of the tray icon can also be used to create a new database.
499 </p>
500 <p>
501 You can also create a new local database from a command line with a Shell tool:
502 </p>
503 <pre>
504 &gt; java -cp h2-*.jar org.h2.tools.Shell
505
506 Welcome to H2 Shell
507 Exit with Ctrl+C
508 [Enter] jdbc:h2:mem:2
509 URL jdbc:h2:./path/to/database
510 [Enter] org.h2.Driver
511 Driver
512 [Enter] sa
513 User your_username
514 Password (hidden)
515 Type the same password again to confirm database creation.
516 Password (hidden)
517 Connected
518
519 sql&gt; quit
520 Connection closed
521 </pre>
522 <p>
523 By default remote creation of databases from a TCP connection or a web interface is not allowed.
524 It's not recommended to enable remote creation of databases due to security reasons.
525 User who creates a new database becomes its administrator and therefore gets the same access to your JVM as H2 has
526 and the same access to your operating system as Java and your system account allows.
527 It's recommended to create all databases locally using an embedded URL, local H2 Console, or the Shell tool.
528 </p>
529 <p>
530 If you really need to allow remote database creation, you can pass <code>-ifNotExists</code> parameter to
531 TCP, PG, or Web servers (but not to the Console tool).
532 Its combination with <code>-tcpAllowOthers</code>, <code>-pgAllowOthers</code>, or <code>-webAllowOthers</code>
533 effectively creates a remote security hole in your system, if you use it, always guard your ports with a firewall
534 or some other solution and use such combination of settings only in trusted networks.
535 </p>
536 <p>
537 H2 Servlet also supports such option.
538 When you use it always protect the servlet with security constraints,
539 see <a href="#usingH2ConsoleServlet">Using the H2 Console Servlet</a> for example;
540 don't forget to uncomment and adjust security configuration for your needs.
541 </p>
542
543 <h2 id="using_server">Using the Server</h2>
544 <p>
545 H2 currently supports three server: a web server (for the H2 Console),
546 a TCP server (for client/server connections) and an PG server (for PostgreSQL clients).
547 Please note that only the web server supports browser connections.
548 The servers can be started in different ways, one is using the <code>Server</code> tool.
549 Starting the server doesn't open a database - databases are opened as soon as a client connects.
550 </p>
551
552 <h3>Starting the Server Tool from Command Line</h3>
553 <p>
554 To start the <code>Server</code> tool from the command line with the default settings, run:
555 </p>
556 <pre>
557 java -cp h2*.jar org.h2.tools.Server
558 </pre>
559 <p>
560 This will start the tool with the default options. To get the list of options and default values, run:
561 </p>
562 <pre>
563 java -cp h2*.jar org.h2.tools.Server -?
564 </pre>
565 <p>
566 There are options available to use other ports, and start or not start parts.
567 </p>
568
569 <h3>Connecting to the TCP Server</h3>
570 <p>
571 To remotely connect to a database using the TCP server, use the following driver and database URL:
572 </p>
573 <ul>
574 <li>JDBC driver class: <code>org.h2.Driver</code>
575 </li><li>Database URL: <code>jdbc:h2:tcp://localhost/~/test</code>
576 </li></ul>
577 <p>
578 For details about the database URL, see also in Features.
579 Please note that you can't connection with a web browser to this URL.
580 You can only connect using a H2 client (over JDBC).
581 </p>
582
583 <h3>Starting the TCP Server within an Application</h3>
584 <p>
585 Servers can also be started and stopped from within an application. Sample code:
586 </p>
587 <pre>
588 import org.h2.tools.Server;
589 ...
590 // start the TCP Server
591 Server server = Server.createTcpServer(args).start();
592 ...
593 // stop the TCP Server
594 server.stop();
595 </pre>
596
597 <h3>Stopping a TCP Server from Another Process</h3>
598 <p>
599 The TCP server can be stopped from another process.
600 To stop the server from the command line, run:
601 </p>
602 <pre>
603 java org.h2.tools.Server -tcpShutdown tcp://localhost:9092 -tcpPassword password
604 </pre>
605 <p>
606 To stop the server from a user application, use the following code:
607 </p>
608 <pre>
609 org.h2.tools.Server.shutdownTcpServer("tcp://localhost:9092", "password", false, false);
610 </pre>
611 <p>
612 This function will only stop the TCP server.
613 If other server were started in the same process, they will continue to run.
614 To avoid recovery when the databases are opened the next time,
615 all connections to the databases should be closed before calling this method.
616 To stop a remote server, remote connections must be enabled on the server.
617 Shutting down a TCP server is protected using the option <code>-tcpPassword</code>
618 (the same password must be used to start and stop the TCP server).
619 </p>
620
621 <h2 id="using_hibernate">Using Hibernate</h2>
622 <p>
623 This database supports Hibernate version 3.1 and newer. You can use the HSQLDB Dialect,
624 or the native H2 Dialect.
625 </p>
626 <p>
627 When using Hibernate, try to use the <code>H2Dialect</code> if possible.
628 When using the <code>H2Dialect</code>,
629 compatibility modes such as <code>MODE=MySQL</code> are not supported.
630 When using such a compatibility mode, use the Hibernate dialect for the
631 corresponding database instead of the <code>H2Dialect</code>;
632 but please note H2 does not support all features of all databases.
633 </p>
634
635 <h2 id="using_toplink">Using TopLink and Glassfish</h2>
636 <p>
637 To use H2 with Glassfish (or Sun AS), set the Datasource Classname to
638 <code>org.h2.jdbcx.JdbcDataSource</code>. You can set this in the GUI
639 at Application Server - Resources - JDBC - Connection Pools,
640 or by editing the file <code>sun-resources.xml</code>: at element
641 <code>jdbc-connection-pool</code>, set the attribute
642 <code>datasource-classname</code> to <code>org.h2.jdbcx.JdbcDataSource</code>.
643 </p>
644 <p>
645 The H2 database is compatible with HSQLDB and PostgreSQL.
646 To take advantage of H2 specific features, use the <code>H2Platform</code>.
647 The source code of this platform is included in H2 at
648 <code>src/tools/oracle/toplink/essentials/platform/database/DatabasePlatform.java.txt</code>.
649 You will need to copy this file to your application, and rename it to .java.
650 To enable it, change the following setting in persistence.xml:
651 </p>
652 <pre>
653 &lt;property
654 name="toplink.target-database"
655 value="oracle.toplink.essentials.platform.database.H2Platform"/&gt;
656 </pre>
657 <p>
658 In old versions of Glassfish, the property name is <code>toplink.platform.class.name</code>.
659 </p>
660 <p>
661 To use H2 within Glassfish, copy the h2*.jar to the directory <code>glassfish/glassfish/lib</code>.
662 </p>
663
664 <h2 id="using_eclipselink">Using EclipseLink</h2>
665 <p>
666 To use H2 in EclipseLink, use the platform class <code>org.eclipse.persistence.platform.database.H2Platform</code>.
667 If this platform is not available in your version of EclipseLink, you can use the OraclePlatform instead in many case.
668 See also <a href="https://wiki.eclipse.org/EclipseLink/Development/Incubator/Extensions/H2Platform">H2Platform</a>.
669 </p>
670
671 <h2 id="using_activemq">Using Apache ActiveMQ</h2>
672 <p>
673 When using H2 as the backend database for Apache ActiveMQ, please use the <code>TransactDatabaseLocker</code>
674 instead of the default locking mechanism. Otherwise the database file will grow without bounds. The problem is that the
675 default locking mechanism uses an uncommitted <code>UPDATE</code> transaction, which keeps the transaction log
676 from shrinking (causes the database file to grow). Instead of using an <code>UPDATE</code> statement, the <code>TransactDatabaseLocker</code> uses
677 <code>SELECT ... FOR UPDATE</code> which is not problematic.
678 To use it, change the ApacheMQ configuration element <code>&lt;jdbcPersistenceAdapter&gt;</code> element, property
679 <code>databaseLocker="org.apache.activemq.store.jdbc.adapter.TransactDatabaseLocker"</code>.
680 However, using the MVCC mode will again result in the same problem. Therefore, please do not use the MVCC mode in this case.
681 Another (more dangerous) solution is to set <code>useDatabaseLock</code> to false.
682 </p>
683
684 <h2 id="using_netbeans">Using H2 within NetBeans</h2>
685 <p>
686 There is a known issue when using the Netbeans SQL Execution Window:
687 before executing a query, another query in the form <code>SELECT COUNT(*) FROM &lt;query&gt;</code> is run.
688 This is a problem for queries that modify state, such as <code>SELECT NEXT VALUE FOR SEQ</code>.
689 In this case, two sequence values are allocated instead of just one.
690 </p>
691
692 <h2 id="using_jooq">Using H2 with jOOQ</h2>
693 <p>
694 jOOQ adds a thin layer on top of JDBC, allowing for type-safe SQL construction,
695 including advanced SQL, stored procedures and advanced data types.
696 jOOQ takes your database schema as a base for code generation.
697 If this is your example schema:
698 </p>
699 <pre>
700 CREATE TABLE USER (ID INT, NAME VARCHAR(50));
701 </pre>
702 <p>
703 then run the jOOQ code generator on the command line using this command:
704 </p>
705 <pre>
706 java -cp jooq.jar;jooq-meta.jar;jooq-codegen.jar;h2-1.4.199.jar;.
707 org.jooq.util.GenerationTool /codegen.xml
708 </pre>
709 <p>
710 ...where <code>codegen.xml</code> is on the classpath and contains this information
711 </p>
712 <pre>
713 &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?>
714 &lt;configuration xmlns="http://www.jooq.org/xsd/jooq-codegen-3.11.0.xsd">
715 &lt;jdbc>
716 &lt;driver>org.h2.Driver&lt;/driver>
717 &lt;url>jdbc:h2:~/test&lt;/url>
718 &lt;user>sa&lt;/user>
719 &lt;password>&lt;/password>
720 &lt;/jdbc>
721 &lt;generator>
722 &lt;database>
723 &lt;includes>.*&lt;/includes>
724 &lt;excludes>&lt;/excludes>
725 &lt;inputSchema>PUBLIC&lt;/inputSchema>
726 &lt;/database>
727 &lt;target>
728 &lt;packageName>org.jooq.h2.generated&lt;/packageName>
729 &lt;directory>./src&lt;/directory>
730 &lt;/target>
731 &lt;/generator>
732 &lt;/configuration>
733 </pre>
734 <p>
735 Using the generated source, you can query the database as follows:
736 </p>
737 <pre>
738 DSLContext dsl = DSL.using(connection);
739 Result&lt;UserRecord&gt; result =
740 dsl.selectFrom(USER)
741 .where(NAME.like("Johnny%"))
742 .orderBy(ID)
743 .fetch();
744 </pre>
745 <p>
746 See more details on <a href="https://www.jooq.org">jOOQ Homepage</a>
747 and in the <a href="https://www.jooq.org/tutorial">jOOQ Tutorial</a>
748 </p>
749
750 <h2 id="web_applications">Using Databases in Web Applications</h2>
751 <p>
752 There are multiple ways to access a database from within web
753 applications. Here are some examples if you use Tomcat or JBoss.
754 </p>
755
756 <h3>Embedded Mode</h3>
757 <p>
758 The (currently) simplest solution is to use the database in the
759 embedded mode, that means open a connection in your application when
760 it starts (a good solution is using a Servlet Listener, see below), or
761 when a session starts. A database can be accessed from multiple
762 sessions and applications at the same time, as long as they run in the
763 same process. Most Servlet Containers (for example Tomcat) are just
764 using one process, so this is not a problem (unless you run Tomcat in
765 clustered mode). Tomcat uses multiple threads and multiple
766 classloaders. If multiple applications access the same database at the
767 same time, you need to put the database jar in the <code>shared/lib</code> or
768 <code>server/lib</code> directory. It is a good idea to open the database when the
769 web application starts, and close it when the web application stops.
770 If using multiple applications, only one (any) of them needs to do
771 that. In the application, an idea is to use one connection per
772 Session, or even one connection per request (action). Those
773 connections should be closed after use if possible (but it's not that
774 bad if they don't get closed).
775 </p>
776
777 <h3>Server Mode</h3>
778 <p>
779 The server mode is similar, but it allows you to run the server in another process.
780 </p>
781
782 <h3>Using a Servlet Listener to Start and Stop a Database</h3>
783 <p>
784 Add the h2*.jar file to your web application, and
785 add the following snippet to your web.xml file (between the
786 <code>context-param</code> and the <code>filter</code> section):
787 </p>
788 <pre>
789 &lt;listener&gt;
790 &lt;listener-class&gt;org.h2.server.web.DbStarter&lt;/listener-class&gt;
791 &lt;/listener&gt;
792 </pre>
793 <p>
794 If your servlet container is already Servlet 5-compatible, use the following
795 snippet instead:
796 </p>
797 <pre>
798 &lt;listener&gt;
799 &lt;listener-class&gt;org.h2.server.web.JakartaDbStarter&lt;/listener-class&gt;
800 &lt;/listener&gt;
801 </pre>
802 <p>
803 For details on how to access the database, see the file <code>DbStarter.java</code>.
804 By default this tool opens an embedded connection
805 using the database URL <code>jdbc:h2:~/test</code>,
806 user name <code>sa</code>, and password <code>sa</code>.
807 If you want to use this connection within your servlet, you can access as follows:
808 </p>
809 <pre>
810 Connection conn = getServletContext().getAttribute("connection");
811 </pre>
812 <p>
813 <code>DbStarter</code> can also start the TCP server, however this is disabled by default.
814 To enable it, use the parameter <code>db.tcpServer</code> in the file <code>web.xml</code>.
815 Here is the complete list of options.
816 These options need to be placed between the <code>description</code> tag
817 and the <code>listener</code> / <code>filter</code> tags:
818 </p>
819 <pre>
820 &lt;context-param&gt;
821 &lt;param-name&gt;db.url&lt;/param-name&gt;
822 &lt;param-value&gt;jdbc:h2:~/test&lt;/param-value&gt;
823 &lt;/context-param&gt;
824 &lt;context-param&gt;
825 &lt;param-name&gt;db.user&lt;/param-name&gt;
826 &lt;param-value&gt;sa&lt;/param-value&gt;
827 &lt;/context-param&gt;
828 &lt;context-param&gt;
829 &lt;param-name&gt;db.password&lt;/param-name&gt;
830 &lt;param-value&gt;sa&lt;/param-value&gt;
831 &lt;/context-param&gt;
832 &lt;context-param&gt;
833 &lt;param-name&gt;db.tcpServer&lt;/param-name&gt;
834 &lt;param-value&gt;-tcpAllowOthers&lt;/param-value&gt;
835 &lt;/context-param&gt;
836 </pre>
837 <p>
838 When the web application is stopped, the database connection will be closed automatically.
839 If the TCP server is started within the <code>DbStarter</code>, it will also be stopped automatically.
840 </p>
841
842 <h3 id="usingH2ConsoleServlet">Using the H2 Console Servlet</h3>
843 <p>
844 The H2 Console is a standalone application and includes its own web server, but it can be
845 used as a servlet as well. To do that, include the <code>h2*.jar</code> file in your application, and
846 add the following configuration to your <code>web.xml</code>:
847 </p>
848 <pre>
849 &lt;servlet&gt;
850 &lt;servlet-name&gt;H2Console&lt;/servlet-name&gt;
851 &lt;servlet-class&gt;org.h2.server.web.WebServlet&lt;/servlet-class&gt;
852 &lt;!--
853 &lt;init-param&gt;
854 &lt;param-name&gt;webAllowOthers&lt;/param-name&gt;
855 &lt;param-value&gt;&lt;/param-value&gt;
856 &lt;/init-param&gt;
857 &lt;init-param&gt;
858 &lt;param-name&gt;trace&lt;/param-name&gt;
859 &lt;param-value&gt;&lt;/param-value&gt;
860 &lt;/init-param&gt;
861 --&gt;
862 &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
863 &lt;/servlet&gt;
864 &lt;servlet-mapping&gt;
865 &lt;servlet-name&gt;H2Console&lt;/servlet-name&gt;
866 &lt;url-pattern&gt;/console/*&lt;/url-pattern&gt;
867 &lt;/servlet-mapping&gt;
868 &lt;!--
869 &lt;security-role&gt;
870 &lt;role-name&gt;admin&lt;/role-name&gt;
871 &lt;/security-role&gt;
872 &lt;security-constraint&gt;
873 &lt;web-resource-collection&gt;
874 &lt;web-resource-name&gt;H2 Console&lt;/web-resource-name&gt;
875 &lt;url-pattern&gt;/console/*&lt;/url-pattern&gt;
876 &lt;/web-resource-collection&gt;
877 &lt;auth-constraint&gt;
878 &lt;role-name&gt;admin&lt;/role-name&gt;
879 &lt;/auth-constraint&gt;
880 &lt;/security-constraint&gt;
881 --&gt;
882 </pre>
883 <p>
884 For details, see also <code>src/tools/WEB-INF/web.xml</code>.
885 </p>
886 <p>
887 If your application is already Servlet 5-compatible, use the servlet class
888 <code>org.h2.server.web.JakartaWebServlet</code> instead.
889 </p>
890 <p>
891 To create a web application with just the H2 Console, run the following command:
892 </p>
893 <pre>
894 build warConsole
895 </pre>
896
897 <h2 id="csv">CSV (Comma Separated Values) Support</h2>
898 <p>
899 The CSV file support can be used inside the database using the functions
900 <code>CSVREAD</code> and <code>CSVWRITE</code>,
901 or it can be used outside the database as a standalone tool.
902 </p>
903
904 <h3>Reading a CSV File from Within a Database</h3>
905 <p>
906 A CSV file can be read using the function <code>CSVREAD</code>. Example:
907 </p>
908 <pre>
909 SELECT * FROM CSVREAD('test.csv');
910 </pre>
911 <p>
912 Please note for performance reason, <code>CSVREAD</code> should not be used inside a join.
913 Instead, import the data first (possibly into a temporary table), create the required indexes
914 if necessary, and then query this table.
915 </p>
916
917 <h3>Importing Data from a CSV File</h3>
918 <p>
919 A fast way to load or import data (sometimes called 'bulk load') from a CSV file is
920 to combine table creation with import.
921 Optionally, the column names and data types can be set when creating the table.
922 Another option is to use <code>INSERT INTO ... SELECT</code>.
923 </p>
924 <pre>
925 CREATE TABLE TEST AS SELECT * FROM CSVREAD('test.csv');
926 CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))
927 AS SELECT * FROM CSVREAD('test.csv');
928 </pre>
929
930 <h3>Writing a CSV File from Within a Database</h3>
931 <p>
932 The built-in function <code>CSVWRITE</code> can be used to create a CSV file from a query.
933 Example:
934 </p>
935 <pre>
936 CREATE TABLE TEST(ID INT, NAME VARCHAR);
937 INSERT INTO TEST VALUES(1, 'Hello'), (2, 'World');
938 CALL CSVWRITE('test.csv', 'SELECT * FROM TEST');
939 </pre>
940
941 <h3>Writing a CSV File from a Java Application</h3>
942 <p>
943 The <code>Csv</code> tool can be used in a Java application even when not using a database at all.
944 Example:
945 </p>
946 <pre>
947 import java.sql.*;
948 import org.h2.tools.Csv;
949 import org.h2.tools.SimpleResultSet;
950 public class TestCsv {
951 public static void main(String[] args) throws Exception {
952 SimpleResultSet rs = new SimpleResultSet();
953 rs.addColumn("NAME", Types.VARCHAR, 255, 0);
954 rs.addColumn("EMAIL", Types.VARCHAR, 255, 0);
955 rs.addRow("Bob Meier", "[email protected]");
956 rs.addRow("John Jones", "[email protected]");
957 new Csv().write("data/test.csv", rs, null);
958 }
959 }
960 </pre>
961
962 <h3>Reading a CSV File from a Java Application</h3>
963 <p>
964 It is possible to read a CSV file without opening a database.
965 Example:
966 </p>
967 <pre>
968 import java.sql.*;
969 import org.h2.tools.Csv;
970 public class TestCsv {
971 public static void main(String[] args) throws Exception {
972 ResultSet rs = new Csv().read("data/test.csv", null, null);
973 ResultSetMetaData meta = rs.getMetaData();
974 while (rs.next()) {
975 for (int i = 0; i &lt; meta.getColumnCount(); i++) {
976 System.out.println(
977 meta.getColumnLabel(i + 1) + ": " +
978 rs.getString(i + 1));
979 }
980 System.out.println();
981 }
982 rs.close();
983 }
984 }
985 </pre>
986
987 <h2 id="upgrade_backup_restore">Upgrade, Backup, and Restore</h2>
988
989 <h3>Database Upgrade</h3>
990 <p>
991 The recommended way to upgrade from one version of the database engine to the next
992 version is to create a backup of the database (in the form of a SQL script) using the old engine,
993 and then execute the SQL script using the new engine.
994 </p>
995
996 <h3>Backup using the Script Tool</h3>
997 <p>
998 The recommended way to backup a database is to create a compressed SQL script file.
999 This will result in a small, human readable, and database version independent backup.
1000 Creating the script will also verify the checksums of the database file.
1001 The <code>Script</code> tool is ran as follows:
1002 </p>
1003 <pre>
1004 java org.h2.tools.Script -url jdbc:h2:~/test -user sa -script test.zip -options compression zip
1005 </pre>
1006 <p>
1007 It is also possible to use the SQL command <code>SCRIPT</code> to create the backup of the database.
1008 For more information about the options, see the SQL command <code>SCRIPT</code>.
1009 The backup can be done remotely, however the file will be created on the server side.
1010 The built in FTP server could be used to retrieve the file from the server.
1011 </p>
1012
1013 <h3>Restore from a Script</h3>
1014 <p>
1015 To restore a database from a SQL script file, you can use the <code>RunScript</code> tool:
1016 </p>
1017 <pre>
1018 java org.h2.tools.RunScript -url jdbc:h2:~/test -user sa -script test.zip -options compression zip
1019 </pre>
1020 <p>
1021 For more information about the options, see the SQL command <code>RUNSCRIPT</code>.
1022 The restore can be done remotely, however the file needs to be on the server side.
1023 The built in FTP server could be used to copy the file to the server.
1024 It is also possible to use the SQL command <code>RUNSCRIPT</code> to execute a SQL script.
1025 SQL script files may contain references to other script files, in the form of
1026 <code>RUNSCRIPT</code> commands. However, when using the server mode, the references script files
1027 need to be available on the server side.
1028 </p>
1029
1030 <p>
1031 If the script was generated by H2 1.4.200 or an older version, add <code>VARIABLE_BINARY</code> option to import it
1032 into more recent version.
1033 </p>
1034
1035 <pre>
1036 java org.h2.tools.RunScript -url jdbc:h2:~/test -user sa -script test.zip -options compression zip variable_binary
1037 </pre>
1038
1039 <h3>Online Backup</h3>
1040 <p>
1041 The <code>BACKUP</code> SQL statement and the <code>Backup</code> tool both create a zip file
1042 with the database file. However, the contents of this file are not human readable.
1043 </p><p>
1044 The resulting backup is transactionally consistent, meaning the consistency and atomicity rules apply.
1045 </p>
1046 <pre>
1047 BACKUP TO 'backup.zip'
1048 </pre>
1049 <p>
1050 The <code>Backup</code> tool (<code>org.h2.tools.Backup</code>) can not be used to create a online backup;
1051 the database must not be in use while running this program.
1052 </p>
1053 <p>
1054 Creating a backup by copying the database files while the database is running is not supported,
1055 except if the file systems support creating snapshots.
1056 With other file systems, it can't be guaranteed that the data is copied in the right order.
1057 </p>
1058
1059 <h2 id="command_line_tools">Command Line Tools</h2>
1060 <p>
1061 This database comes with a number of command line tools. To get more information about a tool,
1062 start it with the parameter '-?', for example:
1063 </p>
1064 <pre>
1065 java -cp h2*.jar org.h2.tools.Backup -?
1066 </pre>
1067 <p>
1068 The command line tools are:
1069 </p>
1070 <ul><li><code>Backup</code> creates a backup of a database.
1071 </li><li><code>ChangeFileEncryption</code> allows changing the file encryption password or algorithm of a database.
1072 </li><li><code>Console</code> starts the browser based H2 Console.
1073 </li><li><code>ConvertTraceFile</code> converts a .trace.db file to a Java application and SQL script.
1074 </li><li><code>CreateCluster</code> creates a cluster from a standalone database.
1075 </li><li><code>DeleteDbFiles</code> deletes all files belonging to a database.
1076 </li><li><code>Recover</code> helps recovering a corrupted database.
1077 </li><li><code>Restore</code> restores a backup of a database.
1078 </li><li><code>RunScript</code> runs a SQL script against a database.
1079 </li><li><code>Script</code> allows converting a database to a SQL script for backup or migration.
1080 </li><li><code>Server</code> is used in the server mode to start a H2 server.
1081 </li><li><code>Shell</code> is a command line database tool.
1082 </li></ul>
1083 <p>
1084 The tools can also be called from an application by calling the main or another public method.
1085 For details, see the Javadoc documentation.
1086 </p>
1087
1088 <h2 id="shell_tool">The Shell Tool</h2>
1089 <p>
1090 The Shell tool is a simple interactive command line tool. To start it, type:
1091 </p>
1092 <pre>
1093 java -cp h2*.jar org.h2.tools.Shell
1094 </pre>
1095 <p>
1096 You will be asked for a database URL, JDBC driver, user name, and password.
1097 The connection setting can also be set as command line parameters.
1098 After connecting, you will get the list of options.
1099 The built-in commands don't need to end with a semicolon, but
1100 SQL statements are only executed if the line ends with a semicolon <code>;</code>.
1101 This allows to enter multi-line statements:
1102 </p>
1103 <pre>
1104 sql&gt; select * from test
1105 ...&gt; where id = 0;
1106 </pre>
1107 <p>
1108 By default, results are printed as a table. For results with many column, consider using the list mode:
1109 </p>
1110 <pre>
1111 sql&gt; list
1112 Result list mode is now on
1113 sql&gt; select * from test;
1114 ID : 1
1115 NAME: Hello
1116
1117 ID : 2
1118 NAME: World
1119 (2 rows, 0 ms)
1120 </pre>
1121
1122 <h2 id="open_office">Using OpenOffice Base</h2>
1123 <p>
1124 OpenOffice.org Base supports database access over the JDBC API. To connect to a H2 database
1125 using OpenOffice Base, you first need to add the JDBC driver to OpenOffice.
1126 The steps to connect to a H2 database are:
1127 </p>
1128 <ul><li>Start OpenOffice Writer, go to [Tools], [Options]
1129 </li><li>Make sure you have selected a Java runtime environment in OpenOffice.org / Java
1130 </li><li>Click [Class Path...], [Add Archive...]
1131 </li><li>Select your h2 jar file (location is up to you, could be wherever you choose)
1132 </li><li>Click [OK] (as much as needed), stop OpenOffice (including the Quickstarter)
1133 </li><li>Start OpenOffice Base
1134 </li><li>Connect to an existing database; select [JDBC]; [Next]
1135 </li><li>Example datasource URL: <code>jdbc:h2:~/test</code>
1136 </li><li>JDBC driver class: <code>org.h2.Driver</code>
1137 </li></ul>
1138 <p>
1139 Now you can access the database stored in the current users home directory.
1140 </p>
1141 <p>
1142 To use H2 in NeoOffice (OpenOffice without X11):
1143 </p>
1144 <ul><li>In NeoOffice, go to [NeoOffice], [Preferences]
1145 </li><li>Look for the page under [NeoOffice], [Java]
1146 </li><li>Click [Class Path], [Add Archive...]
1147 </li><li>Select your h2 jar file (location is up to you, could be wherever you choose)
1148 </li><li>Click [OK] (as much as needed), restart NeoOffice.
1149 </li></ul>
1150 <p>
1151 Now, when creating a new database using the "Database Wizard" :
1152 </p>
1153 <ul><li>Click [File], [New], [Database].
1154 </li><li>Select [Connect to existing database] and the select [JDBC]. Click next.
1155 </li><li>Example datasource URL: <code>jdbc:h2:~/test</code>
1156 </li><li>JDBC driver class: <code>org.h2.Driver</code>
1157 </li></ul>
1158 <p>
1159 Another solution to use H2 in NeoOffice is:
1160 </p>
1161 <ul><li>Package the h2 jar within an extension package
1162 </li><li>Install it as a Java extension in NeoOffice
1163 </li></ul>
1164 <p>
1165 This can be done by create it using the NetBeans OpenOffice plugin.
1166 See also <a href="https://wiki.openoffice.org/wiki/Extensions_development_java">Extensions Development</a>.
1167 </p>
1168
1169 <h2 id="web_start">Java Web Start / JNLP</h2>
1170 <p>
1171 When using Java Web Start / JNLP (Java Network Launch Protocol), permissions tags must be set in the .jnlp file,
1172 and the application .jar file must be signed. Otherwise, when trying to write to the file system, the following
1173 exception will occur: <code>java.security.AccessControlException</code>:
1174 access denied (<code>java.io.FilePermission ... read</code>).
1175 Example permission tags:
1176 </p>
1177 <pre>
1178 &lt;security&gt;
1179 &lt;all-permissions/&gt;
1180 &lt;/security&gt;
1181 </pre>
1182
1183 <h2 id="connection_pool">Using a Connection Pool</h2>
1184 <p>
1185 For H2, opening a connection is fast if the database is already open.
1186 Still, using a connection pool improves performance if you open and close connections a lot.
1187 A simple connection pool is included in H2. It is based on the
1188 <a href="http://www.source-code.biz/miniconnectionpoolmanager/">Mini Connection Pool Manager</a>
1189 from Christian d'Heureuse. There are other, more complex, open source connection pools available,
1190 for example the <a href="https://commons.apache.org/proper/commons-dbcp/">Apache Commons DBCP</a>.
1191 For H2, it is about twice as faster to get a connection from the built-in connection pool than to get
1192 one using <code>DriverManager.getConnection()</code>.The build-in connection pool is used as follows:
1193 </p>
1194 <pre>
1195 import java.sql.*;
1196 import org.h2.jdbcx.JdbcConnectionPool;
1197 public class Test {
1198 public static void main(String[] args) throws Exception {
1199 JdbcConnectionPool cp = JdbcConnectionPool.create(
1200 "jdbc:h2:~/test", "sa", "sa");
1201 for (int i = 0; i &lt; args.length; i++) {
1202 Connection conn = cp.getConnection();
1203 conn.createStatement().execute(args[i]);
1204 conn.close();
1205 }
1206 cp.dispose();
1207 }
1208 }
1209 </pre>
1210
1211 <h2 id="fulltext">Fulltext Search</h2>
1212 <p>
1213 H2 includes two fulltext search implementations. One is using Apache Lucene,
1214 and the other (the native implementation) stores the index data in special
1215 tables in the database.
1216 </p>
1217
1218 <h3>Using the Native Fulltext Search</h3>
1219 <p>
1220 To initialize, call:
1221 </p>
1222 <pre>
1223 CREATE ALIAS IF NOT EXISTS FT_INIT FOR "org.h2.fulltext.FullText.init";
1224 CALL FT_INIT();
1225 </pre>
1226 <p>
1227 You need to initialize it in each database where you want to use it.
1228 Afterwards, you can create a fulltext index for a table using:
1229 </p>
1230 <pre>
1231 CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR);
1232 INSERT INTO TEST VALUES(1, 'Hello World');
1233 CALL FT_CREATE_INDEX('PUBLIC', 'TEST', NULL);
1234 </pre>
1235 <p>
1236 PUBLIC is the schema name, TEST is the table name. The list of column names (comma separated) is optional,
1237 in this case all columns are indexed. The index is updated in realtime.
1238 To search the index, use the following query:
1239 </p>
1240 <pre>
1241 SELECT * FROM FT_SEARCH('Hello', 0, 0);
1242 </pre>
1243 <p>
1244 This will produce a result set that contains the query needed to retrieve the data:
1245 </p>
1246 <pre>
1247 QUERY: "PUBLIC"."TEST" WHERE "ID"=1
1248 </pre>
1249 <p>
1250 To drop an index on a table:
1251 </p>
1252 <pre>
1253 CALL FT_DROP_INDEX('PUBLIC', 'TEST');
1254 </pre>
1255 <p>
1256 To get the raw data, use <code>FT_SEARCH_DATA('Hello', 0, 0);</code>.
1257 The result contains the columns <code>SCHEMA</code> (the schema name),
1258 <code>TABLE</code> (the table name),
1259 <code>COLUMNS</code> (an array of column names), and
1260 <code>KEYS</code> (an array of objects).
1261 To join a table, use a join as in:
1262 <code>SELECT T.* FROM FT_SEARCH_DATA('Hello', 0, 0) FT, TEST T
1263 WHERE FT.TABLE='TEST' AND T.ID=FT.KEYS[0];</code>
1264 </p>
1265 <p>
1266 You can also call the index from within a Java application:
1267 </p>
1268 <pre>
1269 org.h2.fulltext.FullText.search(conn, text, limit, offset);
1270 org.h2.fulltext.FullText.searchData(conn, text, limit, offset);
1271 </pre>
1272
1273 <h3>Using the Apache Lucene Fulltext Search</h3>
1274 <p>
1275 To use the Apache Lucene full text search, you need the Lucene library in the classpath.
1276 Apache Lucene 8.5.2 or binary compatible version is required.
1277 How to do that depends on the application; if you use the H2 Console, you can add the Lucene
1278 jar file to the environment variables <code>H2DRIVERS</code> or
1279 <code>CLASSPATH</code>.
1280 To initialize the Lucene fulltext search in a database, call:
1281 </p>
1282 <pre>
1283 CREATE ALIAS IF NOT EXISTS FTL_INIT FOR "org.h2.fulltext.FullTextLucene.init";
1284 CALL FTL_INIT();
1285 </pre>
1286 <p>
1287 You need to initialize it in each database where you want to use it.
1288 Afterwards, you can create a full text index for a table using:
1289 </p>
1290 <pre>
1291 CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR);
1292 INSERT INTO TEST VALUES(1, 'Hello World');
1293 CALL FTL_CREATE_INDEX('PUBLIC', 'TEST', NULL);
1294 </pre>
1295 <p>
1296 PUBLIC is the schema name, TEST is the table name. The list of column names (comma separated) is optional,
1297 in this case all columns are indexed. The index is updated in realtime. To search the index,
1298 use the following query:
1299 </p>
1300 <pre>
1301 SELECT * FROM FTL_SEARCH('Hello', 0, 0);
1302 </pre>
1303 <p>
1304 This will produce a result set that contains the query needed to retrieve the data:
1305 </p>
1306 <pre>
1307 QUERY: "PUBLIC"."TEST" WHERE "ID"=1
1308 </pre>
1309 <p>
1310 To drop an index on a table
1311 (be warned that this will re-index all of the full-text indices for the entire database):
1312 </p>
1313 <pre>
1314 CALL FTL_DROP_INDEX('PUBLIC', 'TEST');
1315 </pre>
1316 <p>
1317 To get the raw data, use <code>FTL_SEARCH_DATA('Hello', 0, 0);</code>.
1318 The result contains the columns <code>SCHEMA</code> (the schema name),
1319 <code>TABLE</code> (the table name),
1320 <code>COLUMNS</code> (an array of column names),
1321 and <code>KEYS</code> (an array of objects). To join a table, use a join as in:
1322 <code>SELECT T.* FROM FTL_SEARCH_DATA('Hello', 0, 0) FT, TEST T
1323 WHERE FT.TABLE='TEST' AND T.ID=FT.KEYS[0];</code>
1324 </p>
1325 <p>
1326 You can also call the index from within a Java application:
1327 </p>
1328 <pre>
1329 org.h2.fulltext.FullTextLucene.search(conn, text, limit, offset);
1330 org.h2.fulltext.FullTextLucene.searchData(conn, text, limit, offset);
1331 </pre>
1332 <p>
1333 The Lucene fulltext search supports searching in specific column only.
1334 Column names must be uppercase (except if the original columns are double quoted).
1335 For column names starting with an underscore (_), another underscore needs to be added.
1336 Example:
1337 </p>
1338 <pre>
1339 CREATE ALIAS IF NOT EXISTS FTL_INIT FOR "org.h2.fulltext.FullTextLucene.init";
1340 CALL FTL_INIT();
1341 DROP TABLE IF EXISTS TEST;
1342 CREATE TABLE TEST(ID INT PRIMARY KEY, FIRST_NAME VARCHAR, LAST_NAME VARCHAR);
1343 CALL FTL_CREATE_INDEX('PUBLIC', 'TEST', NULL);
1344 INSERT INTO TEST VALUES(1, 'John', 'Wayne');
1345 INSERT INTO TEST VALUES(2, 'Elton', 'John');
1346 SELECT * FROM FTL_SEARCH_DATA('John', 0, 0);
1347 SELECT * FROM FTL_SEARCH_DATA('LAST_NAME:John', 0, 0);
1348 CALL FTL_DROP_ALL();
1349 </pre>
1350
1351 <h2 id="user_defined_variables">User-Defined Variables</h2>
1352 <p>
1353 This database supports user-defined variables. Variables start with <code>@</code> and can be used wherever
1354 expressions or parameters are allowed. Variables are not persisted and session scoped, that means only visible
1355 from within the session in which they are defined. A value is usually assigned using the SET command:
1356 </p>
1357 <pre>
1358 SET @USER = 'Joe';
1359 </pre>
1360 <p>
1361 The value can also be changed using the SET() method. This is useful in queries:
1362 </p>
1363 <pre>
1364 SET @TOTAL = NULL;
1365 SELECT X, SET(@TOTAL, COALESCE(@TOTAL, 1.) * X) F FROM SYSTEM_RANGE(1, 50);
1366 </pre>
1367 <p>
1368 Variables that are not set evaluate to <code>NULL</code>.
1369 The data type of a user-defined variable is the data type
1370 of the value assigned to it, that means it is not necessary (or possible) to declare variable names before using them.
1371 There are no restrictions on the assigned values; large objects (LOBs) are supported as well.
1372 Rolling back a transaction does not affect the value of a user-defined variable.
1373 </p>
1374
1375 <h2 id="date_time">Date and Time</h2>
1376 <p>
1377 Date, time and timestamp values support standard literals:
1378 </p>
1379 <pre>
1380 VALUES (
1381 DATE '2008-01-01',
1382 TIME '12:00:00',
1383 TIME WITH TIME ZONE '12:00:00+01:00',
1384 TIMESTAMP '2008-01-01 12:00:00',
1385 TIMESTAMP WITH TIME ZONE '2008-01-01 12:00:00+01:00'
1386 );
1387 </pre>
1388 <p>
1389 ISO 8601-style datetime formats with T instead of space between date and time parts are also supported.
1390 </p>
1391 <p>
1392 TIME and TIMESTAMP values are preserved without time zone information as local time.
1393 That means if you store the value '2000-01-01 12:00:00' in one time zone, then change time zone of the session
1394 you will also get '2000-01-01 12:00:00', the value will not be adjusted to the new time zone,
1395 therefore its absolute value in UTC may be different.
1396 </p>
1397 <p>
1398 TIME WITH TIME ZONE and TIMESTAMP WITH TIME ZONE values preserve the specified time zone offset
1399 and if you store the value '2008-01-01 12:00:00+01:00' it also remains the same
1400 even if you change time zone of the session,
1401 and because it has a time zone offset its absolute value in UTC will be the same.
1402 TIMESTAMP WITH TIME ZONE values may be also specified with time zone name like '2008-01-01 12:00:00 Europe/Berlin'.
1403 It that case this name will be converted into time zone offset.
1404 Names of time zones are not stored.
1405 </p>
1406
1407 <h2 id="spring">Using Spring</h2>
1408 <h3>Using the TCP Server</h3>
1409 <p>
1410 Use the following configuration to start and stop the H2 TCP server using the Spring Framework:
1411 </p>
1412 <pre>
1413 &lt;bean id = "org.h2.tools.Server"
1414 class="org.h2.tools.Server"
1415 factory-method="createTcpServer"
1416 init-method="start"
1417 destroy-method="stop"&gt;
1418 &lt;constructor-arg value="-tcp,-tcpAllowOthers,-tcpPort,8043" /&gt;
1419 &lt;/bean&gt;
1420 </pre>
1421 <p>
1422 The <code>destroy-method</code> will help prevent exceptions on hot-redeployment or when restarting the server.
1423 </p>
1424
1425 <h2 id="osgi">OSGi</h2>
1426 <p>
1427 The standard H2 jar can be dropped in as a bundle in an OSGi container.
1428 H2 implements the JDBC Service defined in OSGi Service Platform Release 4 Version 4.2 Enterprise Specification.
1429 The H2 Data Source Factory service is registered with the following properties:
1430 <code>OSGI_JDBC_DRIVER_CLASS=org.h2.Driver</code>
1431 and <code>OSGI_JDBC_DRIVER_NAME=H2 JDBC Driver</code>.
1432 The <code>OSGI_JDBC_DRIVER_VERSION</code>
1433 property reflects the version of the driver as is.
1434 </p>
1435 <p>
1436 The following standard configuration properties are supported:
1437 <code>JDBC_USER, JDBC_PASSWORD, JDBC_DESCRIPTION, JDBC_DATASOURCE_NAME, JDBC_NETWORK_PROTOCOL, JDBC_URL, JDBC_SERVER_NAME, JDBC_PORT_NUMBER</code>.
1438 Any other standard property will be rejected.
1439 Non-standard properties will be passed on to H2 in the connection URL.
1440 </p>
1441
1442 <h2 id="jmx">Java Management Extension (JMX)</h2>
1443 <p>
1444 Management over JMX is supported, but not enabled by default.
1445 To enable JMX, append <code>;JMX=TRUE</code> to the database URL when opening the database.
1446 Various tools support JMX, one such tool is the <code>jconsole</code>.
1447 When opening the <code>jconsole</code>, connect to the process where the database is open
1448 (when using the server mode, you need to connect to the server process). Then go to the <code>MBeans</code> section.
1449 Under <code>org.h2</code> you will find one entry per database. The object name of the entry
1450 is the database short name, plus the path (each colon is replaced with an underscore character).
1451 </p>
1452 <p>
1453 The following attributes and operations are supported:
1454 </p>
1455 <ul><li><code>CacheSize</code>: the cache size currently in use in KB.
1456 </li><li><code>CacheSizeMax</code> (read/write): the maximum cache size in KB.
1457 </li><li><code>Exclusive</code>: whether this database is open in exclusive mode or not.
1458 </li><li><code>FileReadCount</code>: the number of file read operations since the database was opened.
1459 </li><li><code>FileSize</code>: the file size in KB.
1460 </li><li><code>FileWriteCount</code>: the number of file write operations since the database was opened.
1461 </li><li><code>FileWriteCountTotal</code>: the number of file write operations since the database was created.
1462 </li><li><code>LogMode</code> (read/write): the current transaction log mode. See <code>SET LOG</code> for details.
1463 </li><li><code>Mode</code>: the compatibility mode (<code>REGULAR</code> if no compatibility mode is used).
1464 </li><li><code>MultiThreaded</code>: true if multi-threaded is enabled.
1465 </li><li><code>Mvcc</code>: true if <code>MVCC</code> is enabled.
1466 </li><li><code>ReadOnly</code>: true if the database is read-only.
1467 </li><li><code>TraceLevel</code> (read/write): the file trace level.
1468 </li><li><code>Version</code>: the database version in use.
1469 </li><li><code>listSettings</code>: list the database settings.
1470 </li><li><code>listSessions</code>: list the open sessions, including currently executing statement (if any) and locked tables (if any).
1471 </li></ul>
1472 <p>
1473 To enable JMX, you may need to set the system properties <code>com.sun.management.jmxremote</code> and
1474 <code>com.sun.management.jmxremote.port</code> as required by the JVM.
1475 </p>
1476 <!-- [close] { --></div></td></tr></table><!-- } --><!-- analytics --></body></html>
1477