Search This Blog

Tuesday 12 March 2013

My First JPA Application

Till date I have always worked with Hibernate's native API. All my projects involved the SessionFactory, Session and other Hibernate APIs. And it works great. So why should I be looking at JPA ?
Fact is Hibernate came before JPA. In fact some of the Hibernate team members were even a part of the Java Specification that created JPA. JPA came about as a part of the overhaul of the EJB specification. It specifies a standard for building persistence layers in standalone and Enterprise applications. So it is something like JDBC. A standardized API that can be implemented by the various persistence providers in the market.
In fact if we look inside the persistence packages (javax.persistence) we shall find tons of annotations, enums and interfaces. Everything needed to build an API.  The only classes found are exceptions and Persistence.java. The last like a start up class used to connect the interface to the underlying persistence provider.
So should we code to JPA ? Tricky question actually. Coding to interfaces is a great idea. The benefits are numerous. However the fact is that most persistence providers provide features beyond those defined by JPA. For example Hibernate supports more identity generators than JPA. So if you use JPA in a project, you might at some point encounter a scenario which calls for use of Hibernate's native functionalities. And once you use Hibernate.... you break the code to interface rule.
This is a personal thing, but I'd rather code to Hibernate and make the most of its power than stick to JPA interfaces solely to leave open the option of replacing Hibernate in the future. I mean the chances of replacing persistence providers once you are into a project is small and would probably indicate that  the design was not well thought of.
All the same its good to know JPA. Being a specification, it will probably keep growing and newer versions would include any missing features. So I decided to try out the same.
I decided to start with the project setup.
  1. The java classes have been placed in the source package. 
  2. Configuration files needed to run JPA are placed in the META-INF folder on the classpath.
  3. All jars needed for Hibernate have been added to the classpath.
  4. The ejb3-persistence-3.3.2.Beta1.jar includes the JPA classes.
  5. hibernate-entitymanager.jar is the JPA Implementation provided by Hibernate.
  6. For logging I have used log4j. As Hibernate includes slf4j in its dependencies, the slf4j-log4j12-1.6.1.jar has been added to ensure all logging happens through log4j. log4j.properties is also on the classpath.
  7. As the database was postgreSQL, the jdbc driver for the same was added to the classpath.
That completes project setup. In the next post I shall look into the code details.

No comments:

Post a Comment