Introduction
In today’s fast-paced software industry, managing data efficiently is a crucial skill. Whether you are working on enterprise applications or small projects, data handling is at the core of Full Stack Java Development Hibernate, one of the most powerful Object Relational Mapping (ORM) tools, simplifies database interactions by bridging the gap between Java applications and relational databases.
But how do you read and save data using Hibernate effectively? This guide will walk you through the process step by step, ensuring you understand Hibernate’s role in streamlining data access in Java applications. With practical examples, you’ll gain confidence in handling data seamlessly, making you stand out in the job market.
By the end of this blog, you’ll not only grasp the theoretical aspects but also have the skills to integrate Hibernate into real-world projects.
What is Hibernate?
Hibernate is an open-source ORM framework that allows developers to interact with databases without writing repetitive SQL queries. It maps Java classes to database tables using XML configuration files or annotations.
Why Use Hibernate?
- Simplifies database operations
- Eliminates boilerplate JDBC code
- Provides HQL (Hibernate Query Language) for querying data
- Supports automatic table creation and caching
With Hibernate, you can focus on writing business logic while Hibernate takes care of the database operations.
Key Features of Hibernate:
- ORM Support: Maps Java objects to database tables.
- HQL (Hibernate Query Language): Allows querying databases using object-oriented syntax.
- Automatic Schema Generation: Simplifies table creation and management.
- Caching: Improves performance by minimizing database access.
- Transaction Management: Provides seamless handling of database transactions.
Why Use Hibernate to Read and Save Data?
When working on Java-based projects, you often need to perform CRUD (Create, Read, Update, Delete) operations. Traditional JDBC requires extensive coding to perform even simple operations, whereas it is easy to read and save data using Hibernate.
Benefits of Using Hibernate:
- Simplified Code: No need to write repetitive SQL queries.
- Cross-Platform Compatibility: Works with multiple databases like MySQL, PostgreSQL, and Oracle.
- Performance Optimization: Features like caching reduce database overhead.
- Automatic Mapping: Eliminates manual mapping between objects and tables.
- Developer-Friendly API: Intuitive and easy to learn.
Setting Up Hibernate for Reading and Saving Data
Before we dive into reading and saving data, let’s set up Hibernate in a Java project.
Step 1: Add Hibernate Dependencies
To use Hibernate, add the required dependencies to your pom.xml if you are using Maven:
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.0.0.Final</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
</dependencies>
Step 2: Configure Hibernate
Create a hibernate.cfg.xml file to configure your database connection:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/yourdb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
Step 3: Create a Java Entity Class
Define a simple POJO (Plain Old Java Object) class to map with the database table.
import javax.persistence.*;
@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String course;
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;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
How to read data?
Hibernate provides two different methods to read data from the database:
- get(): It returns a persistence object of a given class. It returns null when there is no persistence object available.
- load(): It also returns a persistence object of a given class but throws an exception (objectNotFoundException) if the entity is not available in the database.
Difference between get() and load()
Session.get() | Session.load() |
It never returns a proxy object. | It always returns a proxy object. |
It returns null when the entity is not available in the database and continues the execution. | It throws an exception (objectNotFoundException) when the entity is not available in the database and terminates the execution. |
Eager Loading; It hits the database immediately and returns the object. | Lazy Loading; It hits the database only when it tries to retrieve the object. |
They are used for the SELECT operation. | They are used for DELETE and UPDATE operations. |
How to Read Data Using Hibernate
Reading data using Hibernate involves retrieving records from the database using Hibernate Query Language (HQL).
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.util.List;
public class ReadDataExample {
public static void main(String[] args) {
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class).buildSessionFactory();
Session session = factory.getCurrentSession();
try {
// Start a transaction
session.beginTransaction();
// Query to fetch all students
List<Student> students = session.createQuery("from Student").getResultList();
// Display the students
for (Student s : students) {
System.out.println(s.getId() + " - " + s.getName() + " - " + s.getCourse());
}
// Commit the transaction
session.getTransaction().commit();
} finally {
factory.close();
}
}
}
Explanation:
- HQL query (
from Student
) retrieves all records. - Results are stored in a List.
- Data is displayed using a simple loop.
Let us now understand the Session.get() using an example.
How to Save Data?
Hibernate provides different methods to save data into the database:
- save(): It returns a generated identifier and throws an exception when an entity is already available in the database.
- persist (): It returns a void and throws an exception when an entity is already available in the database.
- saveOrUpdate(): It is used to either save or update the entity in the database.
Let us now understand these using some examples.
How to Save Data Using Hibernate
Saving data to a database using Hibernate involves the following steps:
Step 1: Create a Hibernate Session Factory
The SessionFactory is a heavyweight object that initializes Hibernate and manages sessions.
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SaveDataExample {
public static void main(String[] args) {
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class).buildSessionFactory();
Session session = factory.getCurrentSession();
try {
// Create a student object
Student student = new Student();
student.setName("John Doe");
student.setCourse("Java Programming");
// Start a transaction
session.beginTransaction();
// Save the student object
session.save(student);
// Commit the transaction
session.getTransaction().commit();
System.out.println("Data Saved Successfully!");
} finally {
factory.close();
}
}
}
Explanation:
- SessionFactory loads the Hibernate configuration.
- A Session is created to interact with the database.
- Transactions are started and committed to save the entity.
Conclusion
Hibernate revolutionizes the way developers interact with relational databases in Java applications. By automating CRUD operations and simplifying complex SQL queries, Hibernate makes data handling efficient and developer-friendly.
With a clear understanding of how to read and save data using Hibernate, you can confidently integrate it into your projects. Whether you are managing large-scale enterprise data or small datasets, Hibernate provides the flexibility and power you need.
Are you ready to advance your Hibernate skills? Enroll in H2K Infosys comprehensive Java and Hibernate training today to gain hands-on experience and boost your career prospects!