Hibernate 5 - Save or persist an entity example

Posted on February 5, 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 Hibernate, an entity can be persisted or saved into database using the following methods –

  • Session#save() → This method is used save an entity/object into database and return a generated identifier. It will throw an exception if an entity already exists in the database.
  • Session#persist() → This method is used save an entity/object into database and return a void. It will throw an exception if an entity already exists in the database.
  • Session#saveOrUpdate() → This method is used to either save or update an entity in the database.

The following examples demonstrate the use of the above methods.

Project Structure

Review the following project structure.

Hibernate-save-example.png

Jar dependencies

Add the following maven 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>

 

Create an Entity class

Create a Customer entity class under com.boraji.tutorial.hibernate.entity package as follows.

Customer.java

package com.boraji.tutorial.hibernate.entity;

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

/**
 * @author imssbora
 */
@Entity
@Table(name = "CUSTOMER_TBL")
public class Customer {
  @Id
  @Column(name = "CUST_ID")
  private Long id;

  @Column(name = "NAME")
  private String name;

  public Long getId() {
    return id;
  }

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

  public String getName() {
    return name;
  }

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

 

Create a Hibernate utility class

Create a helper class to bootstrap hibernate SessionFactory. Add  the Customer entity to MetadataSources for mapping.

HibernateUtil.java

package com.boraji.tutorial.hibernate;

import java.util.HashMap;
import java.util.Map;

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import com.boraji.tutorial.hibernate.entity.Customer;

/**
 * @author imssbora
 */
public class HibernateUtil {
  private static StandardServiceRegistry registry;
  private static SessionFactory sessionFactory;

  public static SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
      try {
        StandardServiceRegistryBuilder registryBuilder = 
            new StandardServiceRegistryBuilder();

        Map<String, String> settings = new HashMap<>();
        settings.put("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
        settings.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/BORAJI");
        settings.put("hibernate.connection.username", "root");
        settings.put("hibernate.connection.password", "admin");
        settings.put("hibernate.show_sql", "true");
        settings.put("hibernate.hbm2ddl.auto", "update");

        registryBuilder.applySettings(settings);

        registry = registryBuilder.build();

        MetadataSources sources = new MetadataSources(registry)
            .addAnnotatedClass(Customer.class);

        Metadata metadata = sources.getMetadataBuilder().build();

        sessionFactory = metadata.getSessionFactoryBuilder().build();
      } catch (Exception e) {
        System.out.println("SessionFactory creation failed");
        if (registry != null) {
          StandardServiceRegistryBuilder.destroy(registry);
        }
      }
    }
    return sessionFactory;
  }

  public static void shutdown() {
    if (registry != null) {
      StandardServiceRegistryBuilder.destroy(registry);
    }
  }
}

 

Save an entity using save() method

The following example save the Customer entity using the Session#save().

SessionSaveExample.java

package com.boraji.tutorial.hibernate;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.boraji.tutorial.hibernate.entity.Customer;

/**
 * @author imssbora
 */
public class SessionSaveExample {
  public static void main(String[] args) {
    Session session = null;
    Transaction transaction = null;
    try {
      session = HibernateUtil.getSessionFactory().openSession();
      transaction = session.getTransaction();
      transaction.begin();

      Customer customer = new Customer();
      customer.setId(1l);
      customer.setName("Sunil");
      session.save(customer);

      transaction.commit();
    } catch (Exception e) {
      if (transaction != null) {
        transaction.rollback();
      }
      e.printStackTrace();
    } finally {
      if (session != null) {
        session.close();
      }
    }

    HibernateUtil.shutdown();
  }
}

Output

Hibernate: create table CUSTOMER_TBL (CUST_ID bigint not null, NAME varchar(255), primary key (CUST_ID))
Hibernate: insert into CUSTOMER_TBL (NAME, CUST_ID) values (?, ?)

 

Save an entity using persist() method

The following example save the Customer entity using the Session#persist().

SessionPersistExample.java

package com.boraji.tutorial.hibernate;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.boraji.tutorial.hibernate.entity.Customer;

/**
 * @author imssbora
 */
public class SessionPersistExample {
  public static void main(String[] args) {
    Session session = null;
    Transaction transaction = null;
    try {
      session = HibernateUtil.getSessionFactory().openSession();
      transaction = session.getTransaction();
      transaction.begin();

      Customer customer = new Customer();
      customer.setId(2l);
      customer.setName("Joe");
      session.persist(customer);

      transaction.commit();
    } catch (Exception e) {
      if (transaction != null) {
        transaction.rollback();
      }
      e.printStackTrace();
    } finally {
      if (session != null) {
        session.close();
      }
    }

    HibernateUtil.shutdown();
  }
}

Output

Hibernate: insert into CUSTOMER_TBL (NAME, CUST_ID) values (?, ?)

 

Save an entity using saveOrUpdate() method

The following example save the Customer entity using the Session#saveOrUpdate().

SessionSaveOrUpdateExample.java

package com.boraji.tutorial.hibernate;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.boraji.tutorial.hibernate.entity.Customer;

/**
 * @author imssbora
 */
public class SessionSaveOrUpdateExample {
  public static void main(String[] args) {
    Session session = null;
    Transaction transaction = null;
    try {
      session = HibernateUtil.getSessionFactory().openSession();
      transaction = session.getTransaction();
      transaction.begin();

      Customer customer = new Customer();
      customer.setId(3l);
      customer.setName("Mike");
      session.saveOrUpdate(customer);

      transaction.commit();
    } catch (Exception e) {
      if (transaction != null) {
        transaction.rollback();
      }
      e.printStackTrace();
    } finally {
      if (session != null) {
        session.close();
      }
    }
    HibernateUtil.shutdown();
  }
}

Output

Hibernate: select customer_.CUST_ID, customer_.NAME as NAME2_0_ from CUSTOMER_TBL customer_ where customer_.CUST_ID=?
Hibernate: insert into CUSTOMER_TBL (NAME, CUST_ID) values (?, ?)

 

Review the CUSTOMER_TBL table in the database

mysql> desc CUSTOMER_TBL;
+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| CUST_ID | bigint(20)   | NO   | PRI | NULL    |       |
| NAME    | varchar(255) | YES  |     | NULL    |       |
+---------+--------------+------+-----+---------+-------+
2 rows in set (0.05 sec)

mysql> select * from CUSTOMER_TBL;
+---------+-------+
| CUST_ID | NAME  |
+---------+-------+
|       1 | Sunil |
|       2 | Joe   |
|       3 | Mike  |
+---------+-------+
3 rows in set (0.00 sec)
Download Sources