hibernate

Hibernate Load Example

Photo of YatinYatinSeptember 20th, 2017Last Updated: February 20th, 2019
3 245 9 minutes read

Hibernate Session provide different methods to fetch the data (or a single record) from the database. Two of them are –get() andload(). The functionality is similar but there is a difference between the ways they work. In this tutorial, we will demonstrate the use ofload() method in Hibernate using the annotation based configuration.
 
 
 
 
 
 
 

1. Introduction

1.1 Hibernate

  • Object-Relational Mapping or ORM is the programming technique to map application domain model objects to the relational database tables
  • Hibernate is a Java-based ORM tool that provides a framework for mapping application domain objects to the relational database tables and vice versa. It provides reference implementation of Java Persistence API that makes it a great choice as an ORM tool with benefits of loose coupling
  • A Framework that has the option to map plain old Java objects to the traditional database tables with the use of JPA annotations as well asXML based configuration

Fig. 1: Hibernate Overview
Fig. 1: Hibernate Overview

1.2 Hibernate Annotations

  • Hibernate annotations is the newest way to define mappings without a use of anXML file
  • Developers useannotations to provide metadata configuration along with the Java code. Thus, making the code easy to understand
  • XML provides the ability to change the configuration without building the project. Thus, annotations are less powerful than theXML configuration and should only be used for table and column mappings
  • Annotations are preconfigured with sensible default values, which reduce the amount of coding required. For e.g. Class name defaults to Table name and Field names default to Column names

1.2.1 Reference Guide on Hibernate Annotations

Hibernate Annotations are based on the JPA 2 specification. All the JPA annotations are defined in thejavax.persistence.* package. The basic JPA annotations of Hibernate that can be used in an entity are the ones below.

AnnotationModifierDescription
@EntityMarks a class as a Hibernate Entity (Mapped class)
@TableNameMaps this class with a database table specified byname modifier. If thename is not supplied it maps the class with a table having the same name as the class.
@IdMarks this class field as a Primary Key column.
@GeneratedValueInstructs database to generate a value for this field automatically.
@ColumnNameMaps this field with table column specified byname and uses the field name ifname modifier is absent.

1.3 Hibernate Session Interface

In Hibernate, an entity (or a single record) can be obtained from the database using the followingSession interface methods:

  • Session.get(): This method returns a persistence object of the given class with the given identifier. It will returnnull if there is no persistence object
  • Session.load(): This method returns a persistence object of the given class with the given identifier. It will throw an exceptionObjectNotFoundException, if an entity does not exist in the database. Theload() method may return a proxy object instead of a real persistence object
  • Session.byId(): This method is used to obtain a persistence object by its primary identifier

1.3.1 Session Load() Method

Hibernate’sSession interface provides severalload() methods for loading the entities from the database. Eachload() method requires the object’s primary key as a mandatory identifier. In addition to theid, Hibernate also needs to know which class or the entity name need to be used for finding the object with thatid. Let’s look at the different flavors of theload() method available in the Hibernate Session:

  • public Object load(Class classObj, Serializable id) throws HibernateException: This method needs the class type as an argument which developers would like to load along with the uniqueid and returns the populated entity object which developers will cast to the desired type
  • public Object load(String entityName, Serializable id) throws HibernateException: This method asks for the entity name and the uniqueid. The method returns the populated entity object which developers will cast to the desired type
  • public void load(Object obj, Serializable id) throws HibernateException: This method takes an object as an argument which should be the class that developers would like to load and the object should be empty. Hibernate will populate that object with the object developers requested

Session.load()return a proxy object without hitting the database.A proxy object is a temporary object which does not have any values assigned to it except the primary key or the identifier value. Ifno row (or record) corresponding to the requested identifier exists, then it will throw theObjectNotFoundException exception.

Fig. 2: Hibernate Load() Method Workflow Diagram
Fig. 2: Hibernate Load() Method Workflow Diagram

1.3.2 Get() vs. Load() Method

Here are a few differences betweenget() andload() method in Hibernate:

Session.get()Session.load()
Never returns a proxy object.Always returns the proxy object.
Returnsnull when the corresponding record is not found but the execution continues.ThrowsObjectNotFoundException exception when the corresponding record is not found and execution terminates.
Eager Loading, as it hits the database immediately and returns the original object.Lazy Loading, as it hits the database only when it tries to retrieve other properties of the object.
Commonly used for retrieving the data i.e.SELECT operation.Commonly used forDELETE andUPDATE operations.

1.4 Download and Install Hibernate

You can readthis tutorial in order to download and install Hibernate in the Eclipse IDE.

1.5 Download and Install MySQL

You can watchthis video in order to download and install the MySQL database on your Windows operating system.

Now, open up the Eclipse IDE and let’s see how to implement theSession.load() method in Hibernate using Annotation!

2. Hibernate Load Example

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, MySQL database and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 3: Hibernate Load Application Project Structure
Fig. 3: Hibernate Load Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go toFile -> New -> Maven Project.

Fig. 4: Create Maven Project
Fig. 4: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.

Fig. 5: Project Details
Fig. 5: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default:0.0.1-SNAPSHOT.

Fig. 6: Archetype Parameters
Fig. 6: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and apom.xml file will be created. It will have the following code:

pom.xml

<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>HibernateLoad</groupId><artifactId>HibernateLoad </artifactId><version>0.0.1-SNAPSHOT</version></project>

We can start adding the dependencies that developers want like Hibernate, MySQL etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Database & Table Creation

The following MySQL script is used to create a database calledtutorialDb with table:employee. Open MySQL terminal or workbench terminal and execute theSQLscript.

CREATE DATABASE IF NOT EXISTS tutorialDb;USE tutorialDb;DROP TABLE IF EXISTS employee;CREATE TABLE employee (emp_id INT(50) NOT NULL AUTO_INCREMENT, emp_fname VARCHAR(200) DEFAULT NULL, emp_lname VARCHAR(200) DEFAULT NULL,emp_age INT(50) DEFAULT NULL,emp_education VARCHAR(200) DEFAULT NULL,emp_salary INT(100) DEFAULT NULL, PRIMARY KEY (emp_id));INSERT INTO employee (emp_id, emp_fname, emp_lname, emp_age, emp_education, emp_salary) VALUES (1, 'Harry', 'Potter', 23, 'Bachelor Of Technology', 2500);INSERT INTO employee (emp_id, emp_fname, emp_lname, emp_age, emp_education, emp_salary) VALUES (2, 'Java', 'Geek', 25, 'Master Of Technology', 6500);INSERT INTO employee (emp_id, emp_fname, emp_lname, emp_age, emp_education, emp_salary) VALUES (3, 'Daniel', 'Atlas', 32, 'Business Administration', 4500);

If everything goes well, the table will be shown in the MySQL Workbench.

Fig. 7: Database & Table Creation
Fig. 7: Database & Table Creation

3.2 Maven Dependencies

Here, we specify only two dependencies for Hibernate Core and MySQL Connector. The rest dependencies will be automatically resolved by Maven, such as Hibernate JPA and Hibernate Commons Annotations. Theupdated file will have the following code:

pom.xml

<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>HibernateLoad</groupId><artifactId>HibernateLoad</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><dependencies><!-- Hibernate 4.3.6 Final --><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-core</artifactId><version>4.3.6.Final</version></dependency><!-- Mysql Connector --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.21</version></dependency></dependencies><build><finalName>${project.artifactId}</finalName></build></project>

3.3 Java Class Creation

Let’s create the required Java files. Right-click onsrc/main/java folder,New -> Package.

Fig. 8: Java Package Creation
Fig. 8: Java Package Creation

A new pop window will open where we will enter the package name as:com.jcg.hibernate.load.

Fig. 9: Java Package Name (com.jcg.hibernate.load)
Fig. 9: Java Package Name (com.jcg.hibernate.load)

Once the package is created in the application, we will need to create the model and the implementation classes. Right-click on the newly created package:New -> Class.

Fig. 10: Java Class Creation
Fig. 10: Java Class Creation
Want to be a Hibernate Master ?
Subscribe to our newsletter and download the HibernateUltimateGuideright now!
In order to help you master JPA and database programming with Hibernate, we have compiled a kick-ass guide with all the major Hibernate features and use cases! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

A new pop window will open and enter the file name as:Employee. The model class will be created inside the package:com.jcg.hibernate.load.

Fig. 11: Java Class (Employee.java)
Fig. 11: Java Class (Employee.java)

Repeat the step (i.e. Fig. 10) and enter the filename as:AppMain. The implementation class will be created inside the package:com.jcg.hibernate.load.

Fig. 12: Java Class (AppMain.java)
Fig. 12: Java Class (AppMain.java)

3.3.1 Implementation of Model Class

This class is used to map the model attributes with theSQL column names. Add the following code to it:

Employee.java

package com.jcg.hibernate.load;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.Table;@Entity@Table(name="employee")public class Employee {@Id@Column(name = "emp_id")@GeneratedValue(strategy = GenerationType.AUTO)private int employeeId;@Column(name = "emp_fname")private String firstName;@Column(name = "emp_lname")private String lastName;@Column(name = "emp_age")private int age;@Column(name = "emp_education")private String education;@Column(name = "emp_salary")private int salary;public int getEmployeeId() {return employeeId;}public void setEmployeeId(int employeeId) {this.employeeId = employeeId;}public String getFirstName() {return firstName;}public void setFirstName(String firstName) {this.firstName = firstName;}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getEducation() {return education;}public void setEducation(String education) {this.education = education;}public int getSalary() {return salary;}public void setSalary(int salary) {this.salary = salary;}public String toString() {return "\nId: " + employeeId + ", Name: " + firstName + " " + lastName + ", Age: " + age + ", Education: " + education + ", Salary:" + salary + "$\n";}}

3.3.2 Implementation of Utility Class

This class helps in creating theSessionFactory object from the Hibernate configuration file and interacts with the database to perform theSELECT operation. Add the following code to it:

AppMain.java

package com.jcg.hibernate.load;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;public class AppMain {static Session sessionObj;static SessionFactory sessionFactoryObj;// This Method Is Used To Create The Hibernate's SessionFactory Objectprivate static SessionFactory buildSessionFactory() {// Creating Configuration Instance & Passing Hibernate Configuration FileConfiguration configObj = new Configuration();configObj.configure("hibernate.cfg.xml");// Since Hibernate Version 4.x, ServiceRegistry Is Being UsedServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build(); // Creating Hibernate SessionFactory InstancesessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);return sessionFactoryObj;}// This Method Is Used To Display The Records From The Database Table (i.e. Assuming The Records Are Already Present In The Database Table)public static void displayRecords() {Employee empObj;// Opening The Hibernate's Session Object To Start The Database TransactionsessionObj = buildSessionFactory().openSession();// Load The Employee Details Whose Emp Id is '2'int emp_id1 =2;empObj = (Employee)sessionObj.load(Employee.class, new Integer(emp_id1));if(empObj != null) {System.out.println(empObj.toString());}// Load The Employee Details Whose Emp Id is '10'. This Will Throw The 'ObjectNotFoundException' As Record Doesn't Exist In The Databaseint emp_id2 = 10;empObj = (Employee)sessionObj.load(Employee.class, new Integer(emp_id2));if(empObj != null) {System.out.println(empObj.toString());}}public static void main(String[] args) {displayRecords();}}

3.4. Hibernate Configuration File

To configure the Hibernate framework, we need to implement a configuration file i.e.hiberncate.cfg.xml. Right-click onsrc/main/resources folder,New -> Other.

Fig. 13: XML File Creation
Fig. 13: XML File Creation

A new pop window will open and select the wizard as anXML file.

Fig. 14: Wizard Selection
Fig. 14: Wizard Selection

Again, a pop-up window will open. Verify the parent folder location asHibernateLoad/src/main/resources and enter the file name as:hibernate.cfg.xml. Click Finish.

Fig. 15: hibernate.cfg.xml
Fig. 15: hibernate.cfg.xml

Once the file is created, we will include the database configuration and the mapping class details. Add the following code to it:

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-configuration PUBLIC        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><!-- SQL Dialect --><property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property><!-- Database Connection Settings --><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property><property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tutorialDb</property><property name="hibernate.connection.username">root</property><property name="hibernate.connection.password"></property><!-- Echo All Executed SQL To Console --><property name="show_sql">true</property><!-- Specifying Session Context --><property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property><!-- Mapping With Model Class Containing Annotations --><mapping /></session-factory></hibernate-configuration>

Let’s look at some basic details:

  • Here, we instructed Hibernate to connect to a MySQL database namedtutorialDb and the Mapping classes to be loaded
  • We have also instructed Hibernate framework to useMySQLDialect i.e. Hibernate will optimize the generated SQL statements for MySQL
  • This configuration will be used to create a HibernateSessionFactory object
  • show_sql tag will instruct the Hibernate framework to log all theSQL statements on the console

4. Run the Application

To run the Hibernate application, Right-click on theAppMain class-> Run As -> Java Application. Developers can debug the example and see what happens after every step!

Fig. 16: Run Application
Fig. 16: Run Application

5. Project Demo

The code shows the following status as output.

Fig. 17: Load() Operation
Fig. 17: Load() Operation

That’s all for this post. Happy Learning!!

6. Conclusion

In the above code, we have used theSession.load() method to retrieve the Employee with id:2. Hibernate returned the entity from the database. In the case of id:10, Hibernate returnedObjectNotFoundException as the employee record is not present in the database.

That’s all for Hibernate Load tutorial and I hope this article served you whatever you were looking for.

7. Download the Eclipse Project

This was an example of Hibernate Load.

Download
You can download the full source code of this example here:HibernateLoad
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of YatinYatinSeptember 20th, 2017Last Updated: February 20th, 2019
3 245 9 minutes read
Photo of Yatin

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).

Related Articles

Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.