Quick Hibernate Java Persistence API Setup on Java SE
To quickly setup a working Java SE project using Hibernate, download Hibernate Core 3.5.0-CR-1, which also includes EntityManager and Annotations.
Add all jarfiles in the lib/required directory to your project, with the exception of the SLF4J API, which is included in the SLF4J distribution. Download SLF4J, add the slf4j-api jarfile and any slf4j logprovider to the project. If using slf4j-log4j, the LOG4J jarfile of course has to be made available also.
Unfortunately the Java Persistence API is not included in Java SE (yet?) and Hibernate does not provide the necessary classes either. Browsing through Java EE to find the needed packages might get us the javax.persistence package, but leaves us with a NoClassDefFoundError on ProviderUtil.
The easiest way to make the javax.persistence.* and maybe even more importantly the javax.persistence.spi.* (including javax.persistence.spi.ProviderUtil) packages available is to download the EclipseLink distribution. The jlib/jpa directory has a JPA 2 jarfile.
Now we are all set to start coding. First of all we need a META-INF subdirectory in our sources, containing a persistence.xml like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="default" transaction-type="RESOURCE_LOCAL">
<class>package.classname</class>
</persistence-unit>
</persistence>
We won’t add any provider specific properties here, as adding them in code makes our application more configurable.
Important! When ommitting the xmlns attribute, the following error will occur:
Exception in thread "main" javax.persistence.PersistenceException: Invalid persistence.xml.
Error parsing XML (line-1 : column -1): cvc-elt.1: Cannot find the declaration of element 'persistence'.
Now we create our first Persistent POJO:
package entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Person
{
@Id
@GeneratedValue
private int id;
private String name;
public Person()
{
}
public Person(final String name)
{
setName(name);
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getFirstName()
{
return name;
}
public void setName(final String name)
{
this.name = name;
}
}
We have to modify persistence.xml to make JPA aware of entities.Person:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="default" transaction-type="RESOURCE_LOCAL">
<class>entities.Person</class>
</persistence-unit>
</persistence>
Now we are ready to load Hibernate properties, persist our Person and read it from database (which of course has to be already installed and running, we are using H2 Database in this example):
import entities.Person;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import java.util.List;
import java.util.Properties;
public class JPATest
{
private static Properties getHibernateConfig()
{
Properties props = new Properties();
props.setProperty("hibernate.show_sql", "false");
props.setProperty("hibernate.format_sql", "false");
props.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
props.setProperty("hibernate.connection.url", "jdbc:h2:~/test");
props.setProperty("hibernate.connection.username", "sa");
props.setProperty("hibernate.connection.password", "");
props.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
props.setProperty("hibernate.hbm2ddl.auto", "update");
return props;
}
static EntityManagerFactory emf;
static EntityManager em;
@SuppressWarnings("unchecked")
public static void main(String[] param)
{
BasicConfigurator.configure();
Logger.getLogger("org").setLevel(Level.ERROR);
emf = Persistence.createEntityManagerFactory("default", getHibernateConfig());
em = emf.createEntityManager();
Person markus = new Person("Markus");
em.getTransaction().begin();
em.persist(markus);
em.getTransaction().commit();
List persons = em.createQuery("from Person").getResultList();
for (Person p : persons)
{
System.out.println(p.getName());
}
em.close();
emf.close();
}
}