Thursday, December 11, 2008

Playing with Hibernate and JPA under NetBeans

This articleis a good place to start An Introduction to Java Persistence for Client-Side Developers it introduces JPA Java object persistence to an audience unfamiliar with Java enterprise stuff. 

JPA is an object persistence API, one implementation of which is Hibernate which is an ORM layer between your Java code and an SQL database. Hibernate/JPA handle the mapping back and forth. 

The article uses a light java database HSQLDB which can run as a file based or memory based database though any jdbc connected database should work.

The article consists of 2 Java files and an XML config file, to get these running under NetBeans I did the following:

I created a project.

Then I created a place for the config file: META-INF off the src directory and placed the persistence.xml file in there. To create folders in NetBeans click the parent folder (eg Source packages) select New > Other > Folder if it isnt already in the list of types.

I then added the two Java files under a package "addressbook"

META-INF
    persistence.xml

addressbook
    Person.java
    Main.java

Then I downloaded a the HSQLDB stuff and placed it in a directory. I added the hsqldb.jar to the project. 

Hibernate Support was already an installed Plugin on my copy of NetBeans 6.5. Under the Tools > Libraries page I found a few libraries to select from. The library needs to support annotations and a bunch of logging things so I added the Hibernate JPA library to my project. That was all I needed.

Next I set up a script to run HSQLDB as a separate process

java -classpath lib/hsqldb.jar org.hsqldb.Server

and ran the NetBeans project which did as it was expected to do.

No comments: