Tutorial Hibernate 3 with JPA 2

Hello, how are you?

Today we will study about an important framework to persist your model: “Hibernate”.
To do the Hibernate more powerful in this “HelloWorld” we will be integrating it with JPA.
When we mix this two APIs we do not have the need of mapping each model class in some xml file, but the EntityManager will handle it.

To start our work today we need to do some downloads.

Our first download will be the MySQL.
The download link is: http://dev.mysql.com/downloads/mysql/.

MySQL Site Image

To install the MySQL software you just have to apply the Microsoft installation pattern: “Next, Next, Finish”. Be aware about the password that you will type to your database. This password is needed to our XML configuration file.

Let us create a schema to the database by opening the “MySQL Command Line Client” that will be displaying in your Windows/Linux menu.

Hibernate JPA

Type the user/password that you typed in the MySQL installation. Type the command line below:

create database hello;

Push “Enter” and it is done.

Hibernate JPA

Our next download will be the Hibernate 3 library (click here if you want to find another versions to download).

Now we need to download the MySQL database connector (in here you can find other host to download).

The connector is the responsible to do the “talk” between the Hibernate and the database. We will use the MySQL database, but if you want to do with another database, you just have to do the download of the desired connector to your chosen database.

Hibernate API: Inside the file you have downloaded from the website you will find all the libraries that we need. Some of the libraries are: “Hibernate 3”, “JPA 2” and some others are required, soon you will see the libraries required list.
First create a java project of the type “Java Project”, then create a folder named “lib”to put in our downloaded libraries. To our application work correctly we will need the files listed bellow:

  • hibernate-distribution-3.6.0.Final/hibernate3.jar
  • hibernate-distribution-3.6.0.Final/lib/jpa/hibernate-jpa-2.0-api-1.0.0.Final.jar
  • hibernate-distribution-3.6.0.Final/lib/required/*” (All files are required)

Be aware of: The files that you will find inside the folder “required” are obligatory to the Hibernate 3. Copy all files listed above (and do not forget the files in the required folder) to the lib folder.

MySQL connector: As we did with Hibernate 3 library files we will do the same with the connector file. Inside the zip file, that you downloaded, there is a library named “mysql-connector-java-5.1.14-bin.jar”, copy this file into the lib folder.

In the end we will have our lib folder like the image bellow:

Hibernate JPA

We need to create a configuration file named “persistence.xml”. This file is mandatory for Hibernate configuration and it must be inside the folder “src/META-INF”. Take a look at the file dir and the folder structure (if you are reading this tutorial and you have searched other sources but your code still not working, your problem might be the xml headers. Some tutorials have an invalid “header” typed):

<?xml version="1.0" encoding="UTF-8"?>

<persistence version="2.0"
    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_2_0.xsd">
    
    <persistence-unit name="Hello" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        
        <properties>
            <property name="hibernate.show_sql" value="true" />
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/Hello"/>
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password" value="root" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
        </properties>
    </persistence-unit>
</persistence>

I will talk about each line of above code:

  • <persistence-unit name=”Hello” transaction-type=”RESOURCE_LOCAL”>” Two important configurations are present in this line: “unit name” defines to the application the name of the persistence configuration that we will use. In the same file, we are able to have more than one unit name. “transaction-type” sets our transaction type, in our case local. If we were doing a web application we would not need to control the transaction, the container (JBoss, Glassfish …) would do this job for us.
  • <provider>org.hibernate.ejb.HibernatePersistence</provider>” indicates which provider will “work” in our application. In our case we will use Hibernate.
  • “hibernate.show_sql” enables the SQL log to be shown in the console.
  • “javax.persistence.jdbc.driver” which “agent” will handle the database connection, we will use MySQL.
  • “javax.persistence.jdbc.url” our database url with the created schema.
  • “javax.persistence.jdbc.user” and “javax.persistence.jdbc.password” The database user and password. This attributes were defined when you installed the MySQL database. When I did the installation I typed the values “root”/“root”.
  • “hibernate.dialect” Dialect that the Hibernate will use. We will study more about this subject in a future post, by example, how to generate a database script.
  • “hibernate.hbm2ddl.auto” when this option has the true value, the Hibernate will update your tables when needed. If the table do not exist the Hibernate will create it (“CREATE TABLE…”), if you added a column (“ALTER TABLE…”). Just because this is a tutorial we will leave this option enabled, but it is not a good idea leave it activated in a real application. Again I say that it is not a good idea leave this option enabled for a real application. Turn it on only for local test or study.

One last step before we start to write our code. Add the libraries that we downloaded to the project build path. We need to do it so our application can use the libraries benefits.

Right mouse button click on the project: “Properties > Java Build Path”.

Click on Libraries tab and then “Add Jars”.

To finish this configuration, select all files that are inside the lib folder and click the button “Ok”.

Let us create the class “User” in the package “com”. With this model class we will do the CRUD (Create, Read, Update and Delete) operations.

package com;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="user")
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    
    @Column
    private String name;
    
    @Column
    private String password;
    
    @Override
    public boolean equals(Object obj) {
        if(obj instanceof User){
            User user = (User) obj;
            return user.getId() == this.getId();
        }
        
        return false;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Some details about the above code:

  • “@Entity” will indicate to our Provider that this class should be persisted in our database.
  • “@Table” defines the table name that will be written in the database. If you do not define an attribute value to the field “name”, the default will be the same name of the class.
  • “@Id” defines the Id of the class.
  • “GeneratedValue” It is a key that defines that our Id will have a value created automatically using some pattern. In our sample code above we use the pattern AUTO.
  • “@Column” defines the attribute as a database table column. We could also define a name to the database table column by the attribute “name”, just like we did to the “@Table” annotation.

Now we need a class that will create the connection with the database and manager our model class User. Let us create a class named “Main” in the package “com”.

package com;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("Hello");
        EntityManager em = emf.createEntityManager();

        try {
            em.getTransaction().begin();
            
            User user = new User();
            user.setName("abc123");
            user.setPassword("abc123");
            
            em.persist(user);
            
            em.getTransaction().commit();
        }
        catch (Exception e) {
            em.getTransaction().rollback();
            e.printStackTrace();
        }
        finally{
            emf.close();
        }
        
        System.out.println("It is over");
    }
}

Some details about the code above:

  • Notice that our application is a local application; we will need to control the connection manually. That is the reason of the method “beginTransaction”; we need also commit the changes and close the connection.
  • To persist our object User we use the method “em.persist(user);”

Just run the code and you will see a message indication success. To confirm just run a query into the database just like the images below:

Hibernate JPA

Hibernate JPA

Notice that, in the image above, the Hibernate created the insert sql script for us.

One of the greatest advantages of the Hibernate is that when you read an object from your database, it gives to you an object instead line strings. We use the method “find” to locate a database record by its Id:

package com;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("Hello");
        EntityManager em = emf.createEntityManager();

        try {
            em.getTransaction().begin();
            
            User user = em.find(User.class, 1);
            
            System.out.println(user.getName());
            
            em.getTransaction().commit();
        }
        catch (Exception e) {
            em.getTransaction().rollback();
            e.printStackTrace();
        }
        finally{
            emf.close();
        }
        
        System.out.println("It is over");
    }
}

What do we must to do to update our user data? Let us change the user name, take a look how simple it is:

package com;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("Hello");
        EntityManager em = emf.createEntityManager();

        try {
            em.getTransaction().begin();
            
            User user = em.find(User.class, 1);
            
            user.setName("123abc");            
            
            em.getTransaction().commit();
        }
        catch (Exception e) {
            em.getTransaction().rollback();
            e.printStackTrace();
        }
        finally{
            emf.close();
        }
        
        System.out.println("It is over");
    }
}

Hibernate JPA

To remove a record from the database, you just need to use the implemented method of the entity manager named “remove”. In our case you will invoke the method “find” again and then “em.remove (user);

I know this was a long post, but a hope it might help you.

In future posts we will be able to see about relationships and how to do the Ant + Hibernate generate database scripts.

If you have any doubt or any question, just post it.
See you later. o_

16 thoughts on “Tutorial Hibernate 3 with JPA 2

  1. Hi! great tutorial ! but i have a question.
    Do we have to create also the hibernate.cfg.xml file or can all be done only with the persistence.xml?

    Thanks!

    • Hello Switch,

      You will only need to create the cfg file if you want to use the Hibernate Session. If you use only the EntityManager there is no need to create the cfg file.

      Thanks for passing by.

Leave a Comment