Hibernate 5 and JPA 2 - Persist, find, merge and remove example

Posted on March 25, 2017


Technologies used:   JDK 1.8.0_121 | Hibernate 5.2.6.Final | Maven 3.3.9 | MySQL 5.7.12 | Eclipse Mars.2 (4.5.2)

In this post, we will show you how to persist, find, update and remove an entity using the JPA and Hibernate.

EntityManager#persist() → This method is used to save an entity/object into database and return a void. It will throw an exception if an entity already exists in the database.

EntityManager#find() → This method is used to search an entity into a database for a specified primary key.

EntityManager#merge() → This method is used to change the state of an entity from detached to persistence. Using this method we can modify an entity in a database.

EntityManager#remove() → This method is used to remove an entity/object from a database. It will throw an exception if an entity already does not exist in the database.

The following examples demonstrate the use of the above methods.

Project Structure

Review the following project structure.

Hibernate-JPA-save-example.png

Jar dependencies

Add the following jar dependencies in pom.xml file.

 <dependencies>
    <!-- Mysql Connector -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.5</version>
    </dependency>
    <!-- Hibernate 5.2.6 Final -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.2.6.Final</version>
    </dependency>
  </dependencies>

Entity class

Create a Person entity class under com.boraji.tutorial.hibernate.entity package.

Person.java

package com.boraji.tutorial.hibernate.entity;

import java.util.Date;

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

/**
 * @author imssbora
 */
@Entity
@Table(name = "PERSON")
public class Person {
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private long id;

   @Column(name = "FIRST_NAME")
   private String firstName;

   @Column(name = "MIDDLE_NAME")
   private String middleName;

   @Column(name = "LAST_NAME")
   private String lastName;

   @Column(name = "DOB")
   private Date dob;

   // Getter and Setter methods

}

JPA persistence configuration file

Create a persistence.xml file under src/main/java/META-INF folder and write the following code in it.

persistence.xml

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
  version="2.1">

  <persistence-unit name="PERSISTENCE">
    <description> Hibernate JPA Configuration Example</description>
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

    <properties>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/BORAJI" />
      <property name="javax.persistence.jdbc.user" value="root" />
      <property name="javax.persistence.jdbc.password" value="admin" />
      <property name="hibernate.show_sql" value="true" />
      <property name="hibernate.hbm2ddl.auto" value="update" />
    </properties>

  </persistence-unit>

</persistence>

 

JPA helper class

Create a helper class to bootstrap a JPA EntityManagerFactory.

JPAUtil.java

package com.boraji.tutorial.hibernate;

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

/**
 * @author imssbora
 */
public class JPAUtil {
  private static final String PERSISTENCE_UNIT_NAME = "PERSISTENCE";
  private static EntityManagerFactory factory;

  public static EntityManagerFactory getEntityManagerFactory() {
    if (factory == null) {
      factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    }
    return factory;
  }

  public static void shutdown() {
    if (factory != null) {
      factory.close();
    }
  }
}

Persist an entity

The following example persists an entity into a database using the EntityManager#persist() method.

SavePersonExample.java

package com.boraji.tutorial.hibernate;

import java.util.Calendar;

import javax.persistence.EntityManager;

import com.boraji.tutorial.hibernate.entity.Person;
import com.boraji.tutorial.hibernate.util.JPAUtil;

/**
 * @author imssbora
 */
public class SavePersonExample {
   public static void main(String[] args) {

      EntityManager entityManager = null;
      try {
         entityManager = JPAUtil.getEntityManagerFactory().createEntityManager();
         entityManager.getTransaction().begin();

         Person person = new Person();
         person.setFirstName("Thomas");
         person.setMiddleName("Alva");
         person.setLastName("Edison");
         // Set DOB
         Calendar dob = Calendar.getInstance();
         dob.set(Calendar.DATE, 11);
         dob.set(Calendar.MONTH, 02);
         dob.set(Calendar.YEAR, 1947);
         dob.set(Calendar.HOUR_OF_DAY, 0);
         dob.set(Calendar.MINUTE, 0);
         dob.set(Calendar.SECOND, 0);
         dob.set(Calendar.MILLISECOND, 0);
         person.setDob(dob.getTime());

         // Save entity
         entityManager.persist(person);

         entityManager.getTransaction().commit();
         System.out.println("Person saved successfully");
      } catch (Exception e) {
         e.printStackTrace();
         if (entityManager != null) {
            System.out.println("Transaction is being rolled back.");
            entityManager.getTransaction().rollback();
         }
      } finally {
         if (entityManager != null) {
            entityManager.close();
         }
      }
      JPAUtil.shutdown();
   }
}

Output

Hibernate: create table hibernate_sequence (next_val bigint)
Hibernate: insert into hibernate_sequence values ( 1 )
Hibernate: create table PERSON (id bigint not null, DOB datetime, FIRST_NAME varchar(255), LAST_NAME varchar(255), MIDDLE_NAME varchar(255), primary key (id))

Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into PERSON (DOB, FIRST_NAME, LAST_NAME, MIDDLE_NAME, id) values (?, ?, ?, ?, ?)
Person saved successfully

Load an entity

The following example loads an entity from a database using the EntityManager#find() method.

LoadPersonExample.java

package com.boraji.tutorial.hibernate;

import java.text.SimpleDateFormat;

import javax.persistence.EntityManager;

import com.boraji.tutorial.hibernate.entity.Person;
import com.boraji.tutorial.hibernate.util.JPAUtil;

/**
 * @author imssbora
 */
public class LoadPersonExample {
   public static void main(String[] args) {
      EntityManager entityManager = null;
      try {
         entityManager = JPAUtil.getEntityManagerFactory().createEntityManager();
         entityManager.getTransaction().begin();

         Person person = entityManager.find(Person.class, 1l);
         System.out.println("First Name = " + person.getFirstName());
         System.out.println("Middle Name = " + person.getMiddleName());
         System.out.println("Last Name = " + person.getLastName());
         System.out.println("DOB = " + new SimpleDateFormat("yyyy-MM-dd")
               .format(person.getDob()));

         entityManager.getTransaction().commit();
      } catch (Exception e) {
         e.printStackTrace();
         if (entityManager != null) {
            System.out.println("Transaction is being rolled back.");
            entityManager.getTransaction().rollback();
         }
      } finally {
         if (entityManager != null) {
            entityManager.close();
         }
      }

      JPAUtil.shutdown();
   }
}

Output

Hibernate: select person0_.id as id1_0_0_, person0_.DOB as DOB2_0_0_, person0_.FIRST_NAME as FIRST_NA3_0_0_, person0_.LAST_NAME as LAST_NAM4_0_0_, person0_.MIDDLE_NAME as MIDDLE_N5_0_0_ from PERSON person0_ where person0_.id=?
First Name = Thomas
Middle Name = Alva
Last Name = Edison
DOB = 1947-03-11

 

Update an entity

The following example updates an entity into a database using the EntityManager#merge() method.

UpdatePersonExample.java

package com.boraji.tutorial.hibernate;

import java.util.Calendar;

import javax.persistence.EntityManager;

import com.boraji.tutorial.hibernate.entity.Person;
import com.boraji.tutorial.hibernate.util.JPAUtil;

/**
 * @author imssbora
 */
public class UpdatePersonExample {
   public static void main(String[] args) {

      EntityManager entityManager = null;
      try {
         entityManager = JPAUtil.getEntityManagerFactory().createEntityManager();
         entityManager.getTransaction().begin();

         Person person = entityManager.find(Person.class, 1l);
         
         //Detach entity
         entityManager.clear();
         
         // Update DOB
         Calendar dob = Calendar.getInstance();
         dob.setTime(person.getDob());
         dob.set(Calendar.YEAR, 1847);

         person.setDob(dob.getTime());

         entityManager.merge(person);

         entityManager.getTransaction().commit();
         System.out.println("Person updated successfully");
         
      } catch (Exception e) {
         e.printStackTrace();
         if (entityManager != null) {
            System.out.println("Transaction is being rolled back.");
            entityManager.getTransaction().rollback();
         }
      } finally {
         if (entityManager != null) {
            entityManager.close();
         }
      }

      JPAUtil.shutdown();
   }
}

Output

Hibernate: select person0_.id as id1_0_0_, person0_.DOB as DOB2_0_0_, person0_.FIRST_NAME as FIRST_NA3_0_0_, person0_.LAST_NAME as LAST_NAM4_0_0_, person0_.MIDDLE_NAME as MIDDLE_N5_0_0_ from PERSON person0_ where person0_.id=?
Hibernate: select person0_.id as id1_0_0_, person0_.DOB as DOB2_0_0_, person0_.FIRST_NAME as FIRST_NA3_0_0_, person0_.LAST_NAME as LAST_NAM4_0_0_, person0_.MIDDLE_NAME as MIDDLE_N5_0_0_ from PERSON person0_ where person0_.id=?
Hibernate: update PERSON set DOB=?, FIRST_NAME=?, LAST_NAME=?, MIDDLE_NAME=? where id=?
Person updated successfully

Remove an entity

Use EntityManager#remove() method to delete an entity from a database as follows.

DeletePersonExample.java

package com.boraji.tutorial.hibernate;

import javax.persistence.EntityManager;

import com.boraji.tutorial.hibernate.entity.Person;
import com.boraji.tutorial.hibernate.util.JPAUtil;

/**
 * @author imssbora
 */
public class DeletePersonExample {
   public static void main(String[] args) {

      EntityManager entityManager = null;
      try {
         entityManager = JPAUtil.getEntityManagerFactory().createEntityManager();
         entityManager.getTransaction().begin();

         Person person = entityManager.find(Person.class, 1l);
         
         //Remove entity
         entityManager.remove(person);
         
         entityManager.getTransaction().commit();
         System.out.println("Person removed successfully");
      } catch (Exception e) {
         e.printStackTrace();
         if (entityManager != null) {
            System.out.println("Transaction is being rolled back.");
            entityManager.getTransaction().rollback();
         }
      } finally {
         if (entityManager != null) {
            entityManager.close();
         }
      }

      JPAUtil.shutdown();
   }
}

Output

Hibernate: select person0_.id as id1_0_0_, person0_.DOB as DOB2_0_0_, person0_.FIRST_NAME as FIRST_NA3_0_0_, person0_.LAST_NAME as LAST_NAM4_0_0_, person0_.MIDDLE_NAME as MIDDLE_N5_0_0_ from PERSON person0_ where person0_.id=?
Hibernate: delete from PERSON where id=?
Person removed successfully
Download Sources