Tuesday, October 27, 2009

How to start H2 database as a stand alone java process

In order to start H2 database server from a Java application, in a process other than the main process of your application (i.e. stand alone), you should use the java runtime API.

A code sample to do that:
-------------------------

Runtime rt = Runtime.getRuntime();
Process p = rt.exec("java -cp h2*.jar org.h2.tools.Server");


For the Spring users -
If you are using a Spring application with H2, you can configure spring to start your H2 server as described in the H2 documentation. Note that this will start the H2 server in the same process as you java application.
You can use java Runtime API in Spring as well. If you want the database to start before Spring/Hibernate are started you can use ServletContextListener to start the H2 server.


Hibernate Sequence Generator and H2

Below you can find an example of how to create an ORM with a generated id. The id here is generated via H2 database:

The class file:
---------------

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "some_table")
@javax.persistence.SequenceGenerator(name = "SEQ_SOME_TABLE", sequenceName = "SEQ_SOME_TABLE")
public class SomeOrm {

protected Long id;
protected String text;

public SomeOrm() {

}

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_SOME_TABLE")
@Column(name = "some_id")
public Long getId() {
return this.id;
}

public void setId(Long id) {
this.id = id;
}

@Column(name = "text")
public String getText() {
return text;
}

public void setText(String text) {
this.text = text;
}

}

The code for the database table:
-------------------------------------

CREATE SEQUENCE SEQ_SOME_TABLE;

create table some_table (
some_id BIGINT DEFAULT (NEXT VALUE FOR SEQ_SOME_TABLE) not null primary key,
text VARCHAR2
);