Hibernate 5 JPA Tutorial

In this Hibernate 5 JPA Tutorial we will teach you to use Hibernate and JPA together to create a program.

Hibernate 5 JPA Tutorial

Hibernate 5 JPA Tutorial: Write JPA code using Hibernate

In this example I will teach you to integrate Hibernate 5 as persistence provide in JPA based application. In our Java program we will instantiate EntityManagerFactory using Hibernate as persistence provider. Through EntityManager we will perform persist operations to save object into database. We are using MySQL database server to save data as backend server.

About Java Persistence API

Java Persistence API or simple JPA is part of JEE specification for persisting Java objects (POJO classes or Entity) to the relational databases. This specification specifies the API and interfaces for performing CRUD operations on the Entity. Entity is POJO classes which is persisted into relational databases.

Java Persistence API is specification and there any many implementations available on the internet. Many are free open source but few are commercial also. The JPA implementations are:

  • Hibernate - Hibernate is Most Popular ORM framework in Java.
     
  • EclipseLink - This is reference implementation of JPA specification
     
  • Apache OpenJPA - OpenJPA is open source implementation of JPA specification from Apache Software foundation. The Apache OpenJPA is distributed under Apache 2.0 Licence.

Hibernate 5 JPA Tutorial

Java persistence through JPA consists of following major concepts:

  • JPA API - The Java Persistence API which provides interfaces for persisting and interacting with underlying database
     
  • JPA Query API - The query language for performing query on the Entity
     
  • JPA Criteria Query API - The Java Persistence Criteria API for performing conditional query on Entity
     
  • ORM Mapping Meta data - Object/relational mapping metadata uses annotations or xml file. But in most of the project annotations are preferred as it provides easy coding and code management

About Hibernate ORM

Hibernate is popular, most used ORM framework in Java which is used for enterprise application. Hibernate 5 also support NoSQL databases with Hibernate OGM. Hibernate can be used with JPA to write database access code using JPA API. In this tutorial we are using Hibernate 5 and JPA for this sample project.

Writing Hibernate 5 JPA example

Step 1: Create database and table

We are using MySQL database for this tutorial but you can use any of the database. Here is the query to create database and table:

create database jpa;

CREATE TABLE `car` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `car_name` varchar(250) DEFAULT NULL,
  `description` varchar(400) DEFAULT NULL,
  `price` double(10,2) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Step 2: Writing Model class

Model class is simple Java POJO class with the annotation to map it to database table and Java variables in the class to table column. We have Car.java class which is mapped to car table in database. Here is code of Car.java class:

package net.roseindia.model;

import javax.persistence.*;

/**
* @author Deepak Kumar
* More tutorials at http://www.roseindia.net
*/

@Entity
@Table(name="car")
public class Car {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int id;
	
	@Column(name="car_name")
	private String carName;
	
	@Column(name="description")
	private String description;
	
	@Column(name="price")
	private Double price;

	public int getId() {
		return id;
	}

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

	public String getCarName() {
		return carName;
	}

	public void setCarName(String carName) {
		this.carName = carName;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public Double getPrice() {
		return price;
	}

	public void setPrice(Double price) {
		this.price = price;
	}
}

We have used following annotations in the Car.java Entity class:

@Entity - This defines Car.java as an Entity

@Table - Table name to for mapping this entity

@Id - Primary key mapping and it maps the annotated field as primary key

@GeneratedValue - Primay Key generated from database

@Column - Mapping Java variable to table column

Step 3: JPA configuration file - persistence.xml

The persistence.xml file is the configuration file to define persistence context. Here is the full code of the same:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/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_1.xsd">
  <persistence-unit name="psunit1">
 	
		<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
		<class>net.roseindia.model.Car</class>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
            <property name="hibernate.connection.url" 
			value="jdbc:mysql://localhost:3306/jpa?useUnicode=true&characterEncoding=UTF-8"/>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value="root"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            
        </properties>
	
  </persistence-unit>
</persistence>

Since we are using MySQL database we have used the dialect org.hibernate.jpa.HibernatePersistenceProvider. The <class>net.roseindia.model.Car</class> tag is used to provide the name of mapping Entity class.

Other details includes MySQL database driver, user name and password to connect to the database.

Step 4: Add dependency in pom.xml file

Maven build tool is used to build the project and we have added Hibernate 5 and JPA 2.1 dependency in it.

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

Step 5: Code to performing CRUD operation

First we have to get the instance of EntityManager with the help of following code:

factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();

To add data following code is used:

Car car = new Car();
car.setCarName("Zenvo ST1");
car.setDescription("Zenvo ST1 is most expensive Car in world.");
car.setPrice(1200000.00);
em.persist(car);

To fetch data following code can be used:

//Select all the record from Car table
Query query = em.createQuery("SELECT o FROM Car o");
List lst = query.getResultList();
Iterator it = lst.iterator();
while (it.hasNext()){
	Car obj = (Car) it.next();
	System.out.println("Id: "+obj.getId());
	System.out.println("Name: "+obj.getCarName());
	System.out.println("Description: "+obj.getDescription());
	System.out.println("Price: "+obj.getPrice());
}

To update following code is used in our program:

/* Update Example */
//Load and update Entity Example
em.getTransaction().begin();
//find 
Car carObj = em.find(Car.class,1);
carObj.setDescription("Car description Updated");
//update
em.merge(carObj);
//Commit
em.getTransaction().commit();

To delete following code is used in our program:

//Delete Example
em.getTransaction().begin();

//find 
Car cObj = em.find(Car.class,2);
//delete
em.remove(cObj);		
//Commit
em.getTransaction().commit();

Here is the full code of the application:

package net.roseindia;

import java.util.Iterator;
import java.util.List;

import net.roseindia.model.*;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.ParameterMode;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.StoredProcedureQuery;
	/*
	//Compile mvn compile
	//Run: mvn exec:java -Dexec.mainClass="net.roseindia.AppTest"
	
	*/
/**
* @author Deepak Kumar
* More tutorials at http://www.roseindia.net
*/
	
public class AppTest {

private static final String PERSISTENCE_UNIT_NAME = "psunit1";
private static EntityManagerFactory factory;

public static void main(String[] args) {
	factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
	EntityManager em = factory.createEntityManager();

	em.getTransaction().begin();
	
	Car car = new Car();
	car.setCarName("Zenvo ST1");
	car.setDescription("Zenvo ST1 is most expensive Car in world.");
	car.setPrice(1200000.00);
	em.persist(car);
	

	//Select all the record from Car table
	Query query = em.createQuery("SELECT o FROM Car o");
	List lst = query.getResultList();
	Iterator it = lst.iterator();
	while (it.hasNext()){
		Car obj = (Car) it.next();
		System.out.println("Id: "+obj.getId());
		System.out.println("Name: "+obj.getCarName());
		System.out.println("Description: "+obj.getDescription());
		System.out.println("Price: "+obj.getPrice());
	}
	//Commit
	em.getTransaction().commit();
	
	
	/* Update Example */
	//Load and update Entity Eample
	em.getTransaction().begin();
	//find 
	Car carObj = em.find(Car.class,1);
	carObj.setDescription("Car description Updated");
	//update
	em.merge(carObj);
	//Commit
	em.getTransaction().commit();

	//Select all the record from Car table
	query = em.createQuery("SELECT o FROM Car o");
	lst = query.getResultList();
	it = lst.iterator();
	while (it.hasNext()){
		Car obj = (Car) it.next();
		System.out.println("Id: "+obj.getId());
		System.out.println("Name: "+obj.getCarName());
		System.out.println("Description: "+obj.getDescription());
		System.out.println("Price: "+obj.getPrice());
	}
	
	
	//Delete Example
	em.getTransaction().begin();
	
	//find 
	Car cObj = em.find(Car.class,2);
	//delete
	em.remove(cObj);		
	//Commit
	em.getTransaction().commit();
			
			
	em.close();
	
}
}

To run the example right click AppTest.java in Eclipse and run it as Java application. It will display following output:

Jan 22, 2018 9:15:43 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
	name: psunit1
	...]
Jan 22, 2018 9:15:43 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.12.Final}
Jan 22, 2018 9:15:43 PM org.hibernate.cfg.Environment 
INFO: HHH000206: hibernate.properties not found
Jan 22, 2018 9:15:44 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager 
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Jan 22, 2018 9:15:44 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Jan 22, 2018 9:15:44 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/jpa?useUnicode=true&characterEncoding=UTF-8]
Jan 22, 2018 9:15:44 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Jan 22, 2018 9:15:44 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jan 22, 2018 9:15:44 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections 
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jan 22, 2018 9:15:45 PM org.hibernate.dialect.Dialect 
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Jan 22, 2018 9:15:45 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Jan 22, 2018 9:15:45 PM org.hibernate.envers.boot.internal.EnversServiceImpl configure
INFO: Envers integration enabled? : true
Hibernate: 
    insert 
    into
        car
        (car_name, description, price) 
    values
        (?, ?, ?)
Jan 22, 2018 9:15:47 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: 
    select
        car0_.id as id1_0_,
        car0_.car_name as car_name2_0_,
        car0_.description as descript3_0_,
        car0_.price as price4_0_ 
    from
        car car0_
Id: 1
Name: Zenvo ST1
Description: Zenvo ST1 is most expensive Car in world.
Price: 1200000.0
Hibernate: 
    update
        car 
    set
        car_name=?,
        description=?,
        price=? 
    where
        id=?
Hibernate: 
    select
        car0_.id as id1_0_,
        car0_.car_name as car_name2_0_,
        car0_.description as descript3_0_,
        car0_.price as price4_0_ 
    from
        car car0_
Id: 1
Name: Zenvo ST1
Description: Car description Updated
Price: 1200000.0
Hibernate: 
    delete 
    from
        car 
    where
        id=?

In this tutorial you learned to use Hibernate 5 and JPA in a simple application. You can download code of the application and try in your machine.

Download Source code of Hibernate 5 JPA tutorial.

We have 1000s of Hibernate ORM tutorials. Here are Hibernate 5 tutorial links: