Home » Enterprise Java » hibernate » Hibernate Get Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

Hibernate Get Example

Hibernate Session provide different methods to fetch data (or a single record) from the database. Two of them are – get() and load(). The functionality is similar but there is a difference between the ways they work. In this tutorial, we will demonstrate the use of get() method in Hibernate using 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 provides an option to map plain old Java objects to the traditional database tables with the use of JPA annotations as well as XML 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 an XML file
  • Developers use annotations 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 XML 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 the javax.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 by name modifier. If the name 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 by name and uses the field name if name modifier is absent.

1.3 Hibernate Session Interface

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

  • Session.get(): This method returns 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 returns 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 its primary identifier

1.3.1 Session Get() Method

The get() method is very much similar to load() method. This method either accepts an entity name or a class object as an argument. Let’s look at the different flavors of get() method that are available in the Hibernate Session:

  • public Object get(Class classObj, Serializable id) throws HibernateException
  • public Object get(String entityName, Serializable id) throws HibernateException

Session.get() method always hit the database and return the original object from the database. If there is no row corresponding to the requested identifier, this method will return null.

Fig. 2: Hibernate Get() Method Workflow Diagram

Fig. 2: Hibernate Get() Method Workflow Diagram

1.3.2 Get() vs. Load() Method

Here are a few differences between get() and load() method in Hibernate:

Session.get()Session.load()
Never returns a proxy object.Always returns the proxy object.
Returns null when the corresponding record is not found but the execution continues.Throws ObjectNotFoundException when the corresponding record is not found and executions terminate.
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 for DELETE and UPDATE operations.

1.4 Download and Install Hibernate

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

1.5 Download and Install MySQL

You can watch this 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 the Session.get() method in Hibernate using Annotation!

2. Hibernate Get Example

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 7, MySQL database and Maven. Having said that, we have tested the code against JDK 1.8 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 Get Application Project Structure

Fig. 3: Hibernate Get 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 to File -> 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 a pom.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>HibernateGet</groupId>
	<artifactId>HibernateGet</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 called tutorialDb with table: employee. Open MySQL terminal or workbench terminal and execute the SQL script.

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

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. The updated 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>HibernateGet</groupId>
	<artifactId>HibernateGet</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 on src/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.get.

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

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

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

Fig. 10: Java Class Creation

Fig. 10: Java Class Creation

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

Fig. 11: Java Class (Employee.java)

Fig. 11: Java Class (Employee.java)

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

Fig. 12: Java Class (HibernateUtil.java)

Fig. 12: Java Class (HibernateUtil.java)

Again, repeat the step listed in Fig. 10 and enter the file name as AppMain. The implementation class will be created inside the package: com.jcg.hibernate.get.

Fig. 13: Java Class (AppMain.java)

Fig. 13: Java Class (AppMain.java)

3.3.1 Implementation of Model Class

Add the following code to it:

Employee.java

package com.jcg.hibernate.get;

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 "Id: " + employeeId + ", Name: " + firstName + " " + lastName + ", Age: " + age + ", Education: " + education + ", Salary:" + salary + "$\n";
	}
}

3.3.2 Implementation of Utility Class

This class helps in creating the SessionFactory from the Hibernate configuration file and interacts with the database to perform the INSERT and SELECT operations. Add the following code to it:

HibernateUtil.java

package com.jcg.hibernate.get;

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 HibernateUtil {

	static Session sessionObj;
	static SessionFactory sessionFactoryObj;

	// This Method Is Used To Create The Hibernate's SessionFactory Object
	private static SessionFactory buildSessionFactory() {
		// Creating Configuration Instance & Passing Hibernate Configuration File
		Configuration configObj = new Configuration();
		configObj.configure("hibernate.cfg.xml");

		// Since Hibernate Version 4.x, ServiceRegistry Is Being Used
		ServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build(); 

		// Creating Hibernate SessionFactory Instance
		sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);
		return sessionFactoryObj;
	}

	// Method 1: This Method Used To Create A New Employee Record In The Database Table
	public static void createRecord() {		
		Employee empObj;
		int empAge = 26, empSal = 1000;
		try {
			sessionObj = buildSessionFactory().openSession();
			sessionObj.beginTransaction();

			for(int j=101; j <= 105; j++) {
				// Creating Employee Data & Saving It To The Database								
				empObj = new Employee();
				empObj.setFirstName("Editor");
				empObj.setLastName(String.valueOf(j));
				empObj.setAge(empAge);
				empObj.setEducation("Post Graduation");
				empObj.setSalary(empSal);

				empAge = empAge + 3;
				empSal = empSal + 500;

				sessionObj.save(empObj);
			}

			System.out.println("\n.......Records Saved Successfully In The Database.......\n");

			// Committing The Transactions To The Database
			sessionObj.getTransaction().commit();
		} catch(Exception sqlException) {
			if(null != sessionObj.getTransaction()) {
				System.out.println("\n.......Transaction Is Being Rolled Back.......");
				sessionObj.getTransaction().rollback();
			}
			sqlException.printStackTrace();
		} finally {
			if(sessionObj != null) {
				sessionObj.close();
			}
		}
	}

	// Method 2: This Method Is Used To Display The Records From The Database Table
	public static void displayRecords() {
		int emp_id;
		Employee empObj;
		try {
			sessionObj = buildSessionFactory().openSession();

			// Get The Employee Details Whose Emp_Id is 1
			emp_id=1;
			empObj = (Employee)sessionObj.get(Employee.class, new Integer(emp_id));
			if(empObj != null) {
				System.out.println("\nEmployee Record?= " + empObj.toString());
			}

			// Get The Employee Details Whose Emp_Id is 6
			emp_id = 6;
			empObj = (Employee)sessionObj.get(Employee.class, new Integer(emp_id));
			if(empObj != null) {
				System.out.println("\nEmployee Record?= " + empObj.toString());
			} else {
				System.out.println(empObj);
			}
		} catch(Exception sqlException) {
			if(null != sessionObj.getTransaction()) {
				System.out.println("\n.......Transaction Is Being Rolled Back.......");
				sessionObj.getTransaction().rollback();
			}
			sqlException.printStackTrace();
		} finally {
			if(sessionObj != null) {
				sessionObj.close();
			}
		}
	}
}

3.3.3 Implementation of Main Class

Add the following code to it:

AppMain.java

package com.jcg.hibernate.get;

public class AppMain {

	public static void main(String[] args) {
		System.out.println(".......Hibernate Get Example.......\n");

		HibernateUtil.createRecord();

		HibernateUtil.displayRecords();

		System.exit(0);
	}
}

3.4. Hibernate Configuration File

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

Fig. 14: XML File Creation

Fig. 14: XML File Creation

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

Fig. 15: Wizard Selection

Fig. 15: Wizard Selection

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

Fig. 16: hibernate.cfg.xml

Fig. 16: 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 class="com.jcg.hibernate.get.Employee" />
	</session-factory>
</hibernate-configuration>

Notes:

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

4. Run the Application

To run the Hibernate application, Right-click on the AppMain class -> Run As -> Java Application.

Fig. 17: Run Application

Fig. 17: Run Application

5. Project Demo

Executing the AppMain class, you will see the records created in the employee table. Developers can debug the example and see what happens in the database after every step. Enjoy!

Fig. 18: SQL Insert Operation

Fig. 18: SQL Insert Operation

Here after running the Session.get() code we get the following output:

Fig. 19: Get() Operation

Fig. 19: Get() Operation

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

6. Conclusion

In the above code, we have used Session.get() method to retrieve the Employee with id: 1. Hibernate immediately hits the database and returns the original Employee entity. While in case of id: 6, Hibernate returns null as the original Employee entity is not present in the database.

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

7. Download the Eclipse Project

This was an example of Hibernate Get.

Download
You can download the full source code of this example here: Hibernate Get

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

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

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of