Create a persistence xml as follows
Provide the location of the h2*.jar in the value of the property hibernate.connection.url section
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="DefaultPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.url" value="jdbc:h2:c:/lib/test" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"></property>
<property name="hibernate.connection.driver_class" value="org.h2.Driver" />
<property name="hibernate.connection.password" value="sa" />
<property name="hibernate.connection.username" value="sa" />
</properties>
</persistence-unit>
</persistence>
Create an entity as like below
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@Entity
@Table(name = "VEHICLE")
@NamedQuery(name = "Vehicle.findAll", query = "SELECT b FROM Vehicle b")
public class Vehicle {
@Id
@Column(name = "vehicle_number")
private Integer number;
public String getName() {
return name;
}
@Column(name = "vehicle_name")
private String name;
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public void setName(String name) {
this.name = name;
}
}
Below is Test class to test the Hibernate+H2db connection
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
public class TestHibernate {
public static void main(String[] args) {
Vehicle vehicle= new Vehicle();
EntityManager entityManager = Persistence.createEntityManagerFactory("DefaultPersistenceUnit")
.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(vehicle);
entityManager.getTransaction().commit();
entityManager.close();
}
}
Create a table as like below in the h2 browser window
create table VEHICLE
(
code NUMBER(3) not null,
name VARCHAR2(100) not null
)
;