Hibernate 5 - get(), load() and byId() example


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

In Hibernate, an entity can be obtained from a database using the following methods –

Session#get() → This method return a persistence object of the given class with the given identifier. It will return null if there is no persistence object.

Session#load() → This method return a persistence object of the given class with the given identifier. It will throw an exception ObjectNotFoundException, if an entity does not exist in the database. The load() method may return a proxy object instead of a real persistence object.

Session#byId() → This method is used to obtain a persistence object by it primary identifier.

The following examples demonstrate the use of the above methods.

 

Project Structure

Review the following project structure.

 

Demo Database

In this post, we will use the following CUSTOMER_TBL table.

mysql> select * from customer_tbl;
+---------+-------+
| CUST_ID | NAME  |
+---------+-------+
|       1 | Sunil |
|       2 | Joe   |
|       3 | Mike  |
|       4 | Sunil |
+---------+-------+

 

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 follow.

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.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);

            sessionFactory = sources.buildMetadata().buildSessionFactory();

         } 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);
      }
   }
}

 

Create a main class to load an Entity

Here is an example of using the Session#get()Session#load() and Session#byId() methods.

ObtainEntityExample.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 ObtainEntityExample {
   public static void main(String[] args) {
      Session session = null;
      Transaction transaction = null;
      try {
         session = HibernateUtil.getSessionFactory().openSession();
         transaction = session.getTransaction();
         transaction.begin();

         // Obtain an entity using get() method
         Customer customer1 = session.get(Customer.class, 1L);
         if (customer1 != null) {
            System.out.println(customer1.getName());
         }

         // Obtain an entity using load() method
         Customer customer2 = session.load(Customer.class, 2L);
         System.out.println(customer2.getName());
         
         // Obtain an entity using byId() method
         Customer customer3 = session.byId(Customer.class).getReference(3L);
         System.out.println(customer3.getName());
         
         transaction.commit();
      } catch (Exception e) {
         if (transaction != null) {
            transaction.rollback();
         }
         e.printStackTrace();
      } finally {
         if (session != null) {
            session.close();
         }
      }

      HibernateUtil.shutdown();
   }
}

Output

Hibernate: select customer0_.CUST_ID as CUST_ID1_0_0_, customer0_.NAME as NAME2_0_0_ from CUSTOMER_TBL customer0_ where customer0_.CUST_ID=?
Sunil
Hibernate: select customer0_.CUST_ID as CUST_ID1_0_0_, customer0_.NAME as NAME2_0_0_ from CUSTOMER_TBL customer0_ where customer0_.CUST_ID=?
Joe
Hibernate: select customer0_.CUST_ID as CUST_ID1_0_0_, customer0_.NAME as NAME2_0_0_ from CUSTOMER_TBL customer0_ where customer0_.CUST_ID=?
Mike