Tuesday, October 18, 2011

JPA Hello World Program

JPA is a set of specifications with respect to persistence given as part of EJB 3.0. It defines a set of interfaces which are available in the package javax.persistence. Vendors like Hibernate provides meaning implementation for the interfaces and specifications defined in JPA. JDK 5.0 or above is required to support JPA as it uses annotations which are defined starting from JDK 5.0. Here, we will see the examples of JPA with hibernate implementation. At the time of writing this blog, in order to support hiberntate implementation the following jars are required in the class path.


JPA in detail:

JPA requires a folder named META-INF in the class path and this folder is required to contain a xml file named persistence.xml. This xml file will have the JPA configuration details. JPAs specification concentrates on specifying persistence of classes using Java5 annotations, but you can also specify the persistence using metadata. You can define the MetaData in files of any name but the default is "orm.xml", stored under /META-INF MetaData mapping files for JPA have to match the format defined by the XSD for that file.

Primary programming interfaces in Java Persistence:

javax.persistence.Persistence— A startup class that provides a static method for the creation of an EntityManagerFactory.
■ javax.persistence.EntityManagerFactory—
The equivalent to a Hibernate SessionFactory. This runtime object represents a particular persistence unit. It’s thread-safe, is usually handled as a singleton, and provides methods for the creation of EntityManager instances.
■ javax.persistence.EntityManager—
The equivalent to a Hibernate Session.This single-threaded, nonshared object represents a particular unit of work for data access. It provides methods to manage the lifecycle of entity instances and to create Query instances.
■ javax.persistence.Query—
This is the equivalent to a Hibernate Query. An object is a particular JPA query language or native SQL query representation, and it allows safe binding of parameters and provides various methods for the execution of the query.
■ javax.persistence.EntityTransaction—
This is the equivalent to a Hibernate Transaction, used in Java SE environments for the demarcation of RESOURCE_LOCAL transactions. In Java EE, you rely on the standardized javax.transaction.UserTransaction interface of JTA for programmatic transaction demarcation.

The persistence.xml:

Following is the persistence.xml we have used in our example. It is required to be placed inside the folder META-INF.


<persistence 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_1_0.xsd"
version="1.0">

<persistence-unit name="jpaDemo">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver" />
<property name="hibernate.connection.url" value="jdbc:hsqldb:hsql://localhost" />
<property name="hibernate.connection.username" value="sa" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.c3p0.min_size" value="5" />
<property name="hibernate.c3p0.max_size" value="20" />
<property name="hibernate.c3p0.timeout" value="300" />
<property name="hibernate.c3p0.max_statements" value="50" />

<property name="hibernate.c3p0.idle_test_period" value="3000" />
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="create" />
</properties>
</persistence-unit>
</persistence>

* The EntityManagerFactory represents a particular logical data-source configuration in JPA. The configuration of an EMF, together with a set of mapping metadata is called a persistence unit. Every persistent unit needs a name and in our example we named the persistent unit as "jpaDemo".

* The <provider> tag specifies that the underlying ORM engine is Hibernate.

* The rest of the configurations are the hibernate configuration details which will normally be in the hibernate.cfg.xml.

Hello World Example:

Let us go to the package jpa.com.demo.HelloWorld and execute the class HelloWorldExecutor.java

EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpaDemo");

EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();

Hello hello = new Hello();
hello.setName("Johnson");
hello.setMessage("Welcome");
em.persist(hello);
tx.commit();
em.close();

emf.close();

* When the program is executed, the Persistence.createEntityManagerFactory tries to find the persistent unit named "jpdDemo". It searches the classpath for all META-INF/persistence.xml files and then configures the EMF if a match is found.
* The persistence provider tries to find all annotated classess and all Hibernate XML mapping files in the build output directory. Hence automatic detection of annotated classes and xml mapping files is done in JPA.
* Here we reuse the annotated class Hello.java from the package annotation.com.demo.helloworld

Once the
HelloWorldExecutor.java is executed, verify the results in the eclipse console and as well as in the HSQL DB manager as follows.