JPA - Hello, World! using Hibernate

Java Persistence API (JPA) is a Java application programming interface specification that describes the management of relational data in applications using Java Platform, Standard Edition and Java Platform, Enterprise Edition. Various frameworks like Hibernate, EclipseLink and Apache OpenJPA provide object relational mapping according to JPA standards. This tutorial guides you to develop a simple Java Persistence API (JPA) based database application using Hibernate framework and MySQL database. 
Note: If you prefer Hibernate 5, visit to the new tutorial JPA - Hello, World! using Hibernate 5
You need Eclipse for Java EE developers and MySQL server in your system in-order to try this tutorial.
If you prefer to import the necessary libraries manually as shown in "Step 3 Without Maven", Eclipse for Java developers is enough. Those who prefer Maven projects, need to have M2Eclipse plugin in their Eclipse. This tutorial recommends Eclipse for Java EE, since it has M2Eclipse plugin by default. Also please be informed that the project attached at the end of this tutorial is created using Maven.
Step 1:
Create a database “javahelps” and a table “student” in MySQL.
CREATE DATABASE IF NOT EXISTS javahelps;

CREATE  TABLE javahelps.student ( 
student_id INT NOT NULL ,
student_name VARCHAR(45) NOT NULL ,
student_age INT NOT NULL ,
PRIMARY KEY (student_id) );


Step 2:
Create a new Java project “JPAHelloWorld” in Eclipse.


Step 3:
This step has two choices. You can either, convert this project to a Maven project or continue as an ordinary Java project.

With Maven:
Step 3.1:
Convert the project to Maven project by right clicking on the project and selecting Configure → Convert to Maven Project.


Step 3.2:
Give the group id: “com.javahelps” and artifact id: “JPAHelloWorld” in the appeared dialog and Finish the process.


Step 3.3:
Add the following dependencies to pom.xml.
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.3.10.Final</version>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>4.3.10.Final</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.12</version>
</dependency>

<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.20.0-GA</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.36</version>
</dependency>

After the modification, pom.xml should look like this:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.javahelps</groupId>
    <artifactId>JPAHelloWorld</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.10.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.10.Final</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>

        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.20.0-GA</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.36</version>
        </dependency>
    </dependencies>
</project>

Without Maven:
Step 3.1:
Download and extract the Hibernate libraries, from this link: Hibernate ORM.
Download and extract the MySQL JDBC connector, from this link: Download Connector/J

Step 3.2:
Create a new folder “lib” in the project.


Step 3.3:
Copy all the *.jar files from “hibernate-release-xxx/lib/required” folder and paste them into the “lib” folder.
Also, copy the mysql-connector-java-xxx-bin.jar file to "lib" folder of your project.

Step 3.4:
Select all the libraries; right click on them and select Build Path → Add to Build Path. After adding to the Build Path, the libraries have to be listed under Referenced Libraries as shown below:


Step 4:
Create a new package “com.javahelps.jpa

Step 5:
Create a new class Student inside the package as shown below.
package com.javahelps.jpa;

import java.io.Serializable;

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

@Entity
@Table(name = "student")
public class Student implements Serializable {
    @Id
    @Column(name = "student_id", unique = true)
    private int id;

    @Column(name = "student_name", nullable = false)
    private String name;

    @Column(name = "student_age", nullable = false)
    private int age;

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return id + "\t" + name + "\t" + age;
    }
}

Step 6:
Right click on the project and select New → Source Folder.
Give the folder name as “resources' and click on the “Finish” button in the appeared dialog. Inside the resources folder, create a new folder named META-INF.


Step 7:
Create a new file persistence.xml, in the META-INF folder and modify the content as shown below.
<?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="JavaHelps" transaction-type="RESOURCE_LOCAL">
        <!-- Persistence provider -->
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <!-- Entity classes -->
        <class>com.javahelps.jpa.Student</class>
        <properties>
            <!-- The JDBC driver of your database -->
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <!-- The JDBC URL to the database instance -->
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/javahelps" />
            <!-- The database username -->
            <property name="javax.persistence.jdbc.user" value="root" />
            <!-- The database password -->
            <property name="javax.persistence.jdbc.password" value="root" />
        </properties>
    </persistence-unit>
</persistence>
In this configuration file, change the username and password of the database according to your database.

Step 8:
Create a new Java class Main.java with main method.

Step 9:
Create an EntityManagerFactory and initialize it as shown below. The persistence unit name used to create the EntityManagerFactory, should match with the name defined in the persistence.xml file.
package com.javahelps.jpa;

import java.util.List;

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

public class Main {
    // Create an EntityManagerFactory when you start the application.
    private static final EntityManagerFactory ENTITY_MANAGER_FACTORY = Persistence
            .createEntityManagerFactory("JavaHelps");
}

Step 10:
Add the CRUD methods to the Main class and access them from the main method as given below:
package com.javahelps.jpa;

import java.util.List;

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

public class Main {
    // Create an EntityManagerFactory when you start the application.
    private static final EntityManagerFactory ENTITY_MANAGER_FACTORY = Persistence
            .createEntityManagerFactory("JavaHelps");

    public static void main(String[] args) {

        // Create two Students
        create(1, "Alice", 22); // Alice will get an id 1
        create(2, "Bob", 20); // Bob will get an id 2
        create(3, "Charlie", 25); // Charlie will get an id 3

        // Update the age of Bob using the id
        upate(2, "Bob", 25);

        // Delete the Alice from database
        delete(1);

        // Print all the Students
        List students = readAll();
        if (students != null) {
            for (Student stu : students) {
                System.out.println(stu);
            }
        }

        // NEVER FORGET TO CLOSE THE ENTITY_MANAGER_FACTORY
        ENTITY_MANAGER_FACTORY.close();
    }

    /**
     * Create a new Student.
     * 
     * @param name
     * @param age
     */
    public static void create(int id, String name, int age) {
        // Create an EntityManager
        EntityManager manager = ENTITY_MANAGER_FACTORY.createEntityManager();
        EntityTransaction transaction = null;

        try {
            // Get a transaction
            transaction = manager.getTransaction();
            // Begin the transaction
            transaction.begin();

            // Create a new Student object
            Student stu = new Student();
            stu.setId(id);
            stu.setName(name);
            stu.setAge(age);

            // Save the student object
            manager.persist(stu);

            // Commit the transaction
            transaction.commit();
        } catch (Exception ex) {
            // If there are any exceptions, roll back the changes
            if (transaction != null) {
                transaction.rollback();
            }
            // Print the Exception
            ex.printStackTrace();
        } finally {
            // Close the EntityManager
            manager.close();
        }
    }

    /**
     * Read all the Students.
     * 
     * @return a List of Students
     */
    public static List readAll() {

        List students = null;

        // Create an EntityManager
        EntityManager manager = ENTITY_MANAGER_FACTORY.createEntityManager();
        EntityTransaction transaction = null;

        try {
            // Get a transaction
            transaction = manager.getTransaction();
            // Begin the transaction
            transaction.begin();

            // Get a List of Students
            students = manager.createQuery("SELECT s FROM Student s",
                    Student.class).getResultList();

            // Commit the transaction
            transaction.commit();
        } catch (Exception ex) {
            // If there are any exceptions, roll back the changes
            if (transaction != null) {
                transaction.rollback();
            }
            // Print the Exception
            ex.printStackTrace();
        } finally {
            // Close the EntityManager
            manager.close();
        }
        return students;
    }

    /**
     * Delete the existing Student.
     * 
     * @param id
     */
    public static void delete(int id) {
        // Create an EntityManager
        EntityManager manager = ENTITY_MANAGER_FACTORY.createEntityManager();
        EntityTransaction transaction = null;

        try {
            // Get a transaction
            transaction = manager.getTransaction();
            // Begin the transaction
            transaction.begin();

            // Get the Student object
            Student stu = manager.find(Student.class, id);

            // Delete the student
            manager.remove(stu);

            // Commit the transaction
            transaction.commit();
        } catch (Exception ex) {
            // If there are any exceptions, roll back the changes
            if (transaction != null) {
                transaction.rollback();
            }
            // Print the Exception
            ex.printStackTrace();
        } finally {
            // Close the EntityManager
            manager.close();
        }
    }

    /**
     * Update the existing Student.
     * 
     * @param id
     * @param name
     * @param age
     */
    public static void upate(int id, String name, int age) {
        // Create an EntityManager
        EntityManager manager = ENTITY_MANAGER_FACTORY.createEntityManager();
        EntityTransaction transaction = null;

        try {
            // Get a transaction
            transaction = manager.getTransaction();
            // Begin the transaction
            transaction.begin();

            // Get the Student object
            Student stu = manager.find(Student.class, id);

            // Change the values
            stu.setName(name);
            stu.setAge(age);

            // Update the student
            manager.persist(stu);

            // Commit the transaction
            transaction.commit();
        } catch (Exception ex) {
            // If there are any exceptions, roll back the changes
            if (transaction != null) {
                transaction.rollback();
            }
            // Print the Exception
            ex.printStackTrace();
        } finally {
            // Close the EntityManager
            manager.close();
        }
    }
}

Step 11:
Run the project and check the output.

If you want to compare the "JPA project using Hibernate" with a "Pure Hiberate project", compare the configuration file and Main.java of this article with the same pieces of code provided in tutorial: Hibernate - Hello, World! using Annotation Mapping.

Find the Maven project at Git Hub.
Previous
Next Post »

11 comments

Write comments
Slowhand
AUTHOR
March 13, 2016 at 11:08 PM delete

When building without Maven, the following jar: "hibernate-entitymanager-5.1.0.Final.jar" has to be added from the "hibernate-release-xxx/lib/jpa” as it is not in "hibernate-release-xxx/lib/required”.

Other than that it worked 2016.03.13.

Reply
avatar
Yoshi
AUTHOR
July 5, 2016 at 10:04 PM delete

Seems to work great! A few things:

In Main, instantiate the List as List, otherwise you'll have problems (because Java).

Also, here's a super simple method to truncate the table if you want to run this code more than once. Just add to Main and run it before anything else:

public static void cleanup() {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
em.getTransaction().begin();
em.createNativeQuery("truncate table student").executeUpdate();
em.getTransaction().commit();
}


Otherwise, great tutorial. Thanks!

Reply
avatar
Gobinath
AUTHOR
July 6, 2016 at 3:21 PM delete

Thank you Yoshi :-)

Reply
avatar
rozie
AUTHOR
October 4, 2016 at 3:01 PM delete

hello there... how to run the apps? right click->Run As->Java Application then need to choose what? TQ in advance...

Reply
avatar
Gobinath
AUTHOR
October 4, 2016 at 7:52 PM delete

Hi,
Once you select "Run as Java Application", you must get the output in console. Also you can see the created student details in the database.

Reply
avatar
rozie
AUTHOR
October 7, 2016 at 7:32 AM delete

Tq very much for your reply. But i got this error. INFO: HHH000204: Processing PersistenceUnitInfo [
name: JavaHelps
...]
Exception in thread "main" java.lang.IncompatibleClassChangeError: Implementing class

what should i do to resolve this error? Tq again Gobinath..

Reply
avatar
Gobinath
AUTHOR
October 7, 2016 at 10:10 AM delete

Hi,
Make sure that you are using the same dependencies as given in this article. If you use latest version of Hibernate, it may not work. I will post a new article for the current Hibernate version soon. If it does not help, please share the complete error log.

Reply
avatar
rozie
AUTHOR
October 7, 2016 at 2:07 PM delete

thanks a lot... i will try using the same dependencies...

Reply
avatar
Gobinath
AUTHOR
October 9, 2016 at 7:54 PM delete

Hi,
I have written a new tutorial on Hibernate 5. Please find it here: http://www.javahelps.com/2016/10/jpa-hello-world-using-hibernate-5.html

Reply
avatar
rozie
AUTHOR
October 10, 2016 at 6:46 AM delete

noted. will try it... thanks...

Reply
avatar

Contact Form

Name

Email *

Message *