Slingshot Yourself Into Hibernate 3.5 and JPA 2.0 with this Tutorial

Tutorial:

Slingshot Yourself Into Hibernate 3.5 and JPA 2.0 with this Tutorial

By Andrew Tee & Cameron McKenzie

TheServerSide.com

Cameron McKenzie is the author of Hibernate Made Easy and the Editor in Chief of TheServerSide.com

Video Tutorials on Learning Hibernate
Hibernate Made Easy WebSite
Recommended Books for Learning Hibernate
My Similarly Coloured Book on The Simpsons
Check out these updated Tutorials for Spring 3 as well.


Do you want to learn Hibernate 3.5, and work with the first release of Hibernate that fully supports JPA 2.0, but you don't want to be led by the nose through any lengthy or long winded tutorials. Well, here it is - the best tutorial you're going to find for getting you started with Hibernate 3.5 in a hurry.

Get The Required Hibernate JAR Files

To work with Hibernate 3.5, you need to link your runtime and design time Java environments to the following JAR files:

  • antlr-2.7.6.jar
  • commons-collections-3.1.jar
  • dom4j-1.6.1.jar
  • hibernate3.jar
  • hibernate-jpa-2.0-api-1.0.0.Final.jar
  • javassist-3.9.0.GA.jar
  • jta-1.1.jar
  • slf4j-api-1.5.8.jar
  • slf4j-simple-1.5.8.jar

You will find all of these JAR files, with the exception of the slf4j-simple-1.5.8.jar file, in the Hibernate 3.5 distribution download. Here's where you can download it:

http://sourceforge.net/projects/hibernate/files/hibernate3/

When you download this zip file, the hibernate3.jar file will be in the root folder of the download. The hibernate-jpa JAR file will be in a subfolder named jpa. The other JAR files, with the exception of slf4j-simple-1.5.8.jar, will be in a folder named required

Create a folder off the root of your C:\ drive named _hiblib3.5 and chuck these JAR files into it.

Find the Darn slf4j-simple-1.5.8.jar File

I'm not sure what the crazy licensing restriction is that allows Hibernate to distribute the slf4j-api jar file, but not the implementation file, but the fact is, the JAR file that provides an actual implementation of the interfaces defined in the slf4j-api-1.5.8.jar file is not provided with the Hibernate distribution download, so you're required to head over to http://www.slf4j.org/download.html and download the 1.5.8 implementation of slf4j. 

Now, as of writing, the latest implementation of slf4j is 1.6, and if you download that one and link to it at design time, you'll get a runtime error, so make sure you get an implementation that matches the version of the slf43-api JAR file that came with the Hibernate distribution you have downloaded (for me it's 1.5.8).

Unzip the downloaded file from slf4j.org, and find the slf4j-simple-1.5.8.jar file, and throw it into your C:\_hiblib3.5 folder. You should now have all nine of the required JAR files in there.

Make Sure You Have Your JDBC Drivers

What? You thought you could learn Hibernate but avoid the database? Yeah...Right...

We're going to connect to a database, so that means you need a database and the JDBC drivers that go along with it. I'm using MySQL, so that means I'm using the mysql-connector-java-5.1.12-bin.jar file, which can be obtained from the Connector/J download page at dev.mysql.com/downloads/connector/j/

This JAR file, or whatever JAR file you use to connect to your database of choice, must be on your Java runtime and design time classpaths. To make life simple, I'm adding this JAR to my C:\_hiblib3.5 folder as well, taking the JAR count in there to an even ten.

Create Your rps Schema in the MySQL Workbench

You'll also need to configure a logical database within your RDBMS system. For MySQL, that means going into the MySQL Workbench and creating a new schema name rps. I'm naming the schema rps, because this database will be holding the results of our online Rock-Paper-Scissors game.

Create & Configure the hibernate.cfg.xml File

You need to tell the Hibernate framework how to connect to your database, and that is done by creating a file named hibernate.cfg.xml, and placing it on your classpath. This file contains the credentials for connecting to your database, the JDBC URL, the dialect, the name of the JDBC driver, and a couple of other tidbits just to keep things interesting. Here's what my hibernate.cfg.xml file looks like, although you may need to tweak yours depending on how your personal environment is configured:


<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
 <property name="connection.url">
    jdbc:mysql://localhost/rps
  </property>
  <property name="connection.username">
    root
  </property>
  <property name="connection.password">
  password
  </property>
  <property name="connection.driver_class">
  com.mysql.jdbc.Driver
  </property>
  <property name="dialect">
  org.hibernate.dialect.MySQLDialect
  </property>
  <property name="current_session_context_class">
  thread
  </property>
  <!-- this will show us all sql statements -->
  <property name="hibernate.show_sql">
  true
  </property>
  <!-- mapping files NOTICE WE HAVE NONE-->
  </session-factory>
</hibernate-configuration>


Save that file with the name hibernate.cfg.xml, and put it on both your runtime and designtime classpath. People always shove it on their design-time classpath, and then it never gets picked up at runtime, and they get errors stating that the environment can't find the hiberante.cfg.xml file. For me, I'm just creating a simple folder named _mycode off the root of C:\ and I'm placing the file right in there. I will reference this location at both runtime and design time.

Write Some Java Code

Hibernate is a persistence framework that saves the state of your Java objects (POJOs) to the database. So, if you want to use Hibernate, you need to create some POJOs. I'm going to start small, with a GameSummary class that has a single property of type String, representing the results of a single game play, and a property of type Long that will represent the unique identifier the database provides to the instance. Every object to be persisted by the Hibernate framework needs some type of identifier that represents its uniqueness, otherwise JPA based persistence simply won't work. Here's what our JPA annotated GameSummary class looks like:


package com.mcnz.model;

import javax.persistence.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.tool.hbm2ddl.*;

@Entity
public class GameSummary {

 @Id
 @GeneratedValue
  private Long id;


  private String result;

  public Long getId() {return id;}

  public void setId(Long id) {
    this.id = id;
  }

  public String getResult() {return result;}

  public void setResult(String result) {
    this.result = result;
  }

  public String toString() {
    return "id: " + id + " result: " + result ;   
 }

}


We have been a bit progressive with our imports, as they are not all needed right now, but they will be soon. For now, focus on the annotations that come from the JPA 2.0 API. The @Entity annotation indicates to the persistence framework that the GameSummary is indeed a persistent class whose state can be managed by Hibernate. The @Id and @GeneratedValue annotations indicate that the primary key for this class is named id, and is of type Long. Furthermore, the database will be responsible for creating unique ids for new instances that are persisted.

By the way, I simply saved this class in a file named GameSummary.java, in a folder name com\mcnz\model under the C:\_mycode directory. If you're using a crazy IDE like NetBeans or Eclipse, you probably won't need to worry about such things, as the folder structures are created and managed for you. You are responsible however for making sure the required JAR files and the hibernate.cfg.xml file will be on your runtime and design time classpaths.

Write Some Test Code

So, does all of this work? Well, that really is the question, isn't it? Add the following main method to your GameSummary class and run it.


public static void main(String args[]) {
 AnnotationConfiguration config = new AnnotationConfiguration();
 config.addAnnotatedClass(GameSummary.class);
 config.configure();
 new SchemaExport(config).create(true, true);
}


File and Sanity Check


At this point, we have talked about a number of differernt JARs, folder and files. Here's what your environment should look like, if you've been following along:

C:\
++ _hiblib3.5\

++++ antlr-2.7.6.jar
++++commons-collections-3.1.jar
++++ dom4j-1.6.1.jar
++++ hibernate3.jar
++++ hibernate-jpa-2.0-api-1.0.0.Final.jar
++++ javassist-3.9.0.GA.jar
++++ jta-1.1.jar
++++ mysql-connector-java-5.1.12-bin.jar
++++ slf4j-api-1.5.8.jar
++++ slf4j-simple-1.5.8.jar

++ _mycode\
++++ hibernate.cfg.xml
++++ com\mcnz\model\GameSummary.java


Run Your Stand Alone Hibernate Application

I have my JDK installed to a folder named C:\_jdk1.6; so, to compile this code, and link to the required libraries, I simply run the following command at the DOS prompt:

C:\>c:\_jdk1.6\bin\javac -classpath "C:\_hiblib3.5\*" C:\_mycode\com\mcnz\model\GameSummary.java

To run this code, I run the following command:

C:\>c:\_jdk1.6\bin\java -classpath "C:\_hiblib3.5\*";C:\_mycode com.mcnz.model.ameSummary

Now it doesn't get any more hard-core and old-school than using the old JDK to compile and run your code. But the point is, if you have followed these instructions, your code will compile and run, and you don't need any fancy-dancy or expensive IDE like Eclipse or NetBeans to do it. And with that said, if I can get this to work with nothing other than a JDK and a few folders containing various JAR files, if you do have a funky development environment, then you shouldn't have any problem getting this tutorial to run there as well.


When the code runs, the Hibernate configuration, which is in essence the instance of the AnnotationConfiguration object, adds the GameSummary.class to its list of classes whose persistence it manages, and the it configures itself, making sure that the Hibernate framework really understands all of the various classes it is tasked with managing. From there, the config object is passed to the SchemaExport's constructor, and a create call is issued. This call looks at the Hibernate AnnotationConfiguration object and creates all of the underlying tables that are needed to support all of the persistent classes it is managing. So, if you run this code, you will see the following output in your console window:

drop table if exists GameSummary
create table GameSummary (id bigint not null auto_increment, result varchar(255), primary key (id))

And if you look at your database, the following table and columns will have been added to your rps database schema:

And if all this happens, well, that means you followed these instructions properly, and your Hibernate environment is up and running!

And that's it for getting your environment configured. If you got that to work, you're ready to move on to the next, much easier step, which is actually persisting some data to the database.

Part II: Performing CRUD Operations with Hibernate 3.5 and JPA Annotations

Cameron McKenzie is the author of Hibernate Made Easy and the Editor in Chief of TheServerSide.com

Video Tutorials on Learning Hibernate
Hibernate Made Easy WebSite
Recommended Books for Learning Hibernate
My Similarly Coloured Book on The Simpsons
Check out these updated Tutorials for Spring 3 as well.


 

20 Jun 2010