Table of contents
1.
Introduction
2.
Hibernate Sessions
2.1.
transient
2.2.
persistent
2.3.
detached
3.
Method of Session Interface in Hibernate
4.
Hibernate session creation example
5.
Advantages of Hibernate Session
6.
Frequently Asked Questions
6.1.
Is the SessionFactory object thread-safe?
6.2.
What is Session?
6.3.
Is a session object thread-safe?
6.4.
Define persistent class.
7.
Conclusion
Last Updated: Mar 27, 2024

Hibernate Sessions

Author Ayush Mishra
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hibernate is a free and open-source object-relational mapping (ORM) program that offers a framework for relational mapping databases to object-oriented domain models for web applications. Java is used to create the Hibernate framework, which provides persistent logic. Data processing and archival storage are referred to as persistence logic.

In this blog, we will discuss the hibernate sessions used to get a physical connection with a database. Let's get going!

Hibernate Sessions

A session is used to establish a physical connection with the database. Each time a database interaction is required, the session object, which is small and designed to be instantiated, is needed. A session object serves as the storage and retrieval mechanism for persistent objects.

A session objects are typically not thread-safe; they should only be created and removed when necessary. The primary purpose of the Session is to provide operations to create, read, and destroy instances of mapped entity classes.

A session instance exists in the following state:-

transient

Hibernate classifies as transient a new instance of a persistent class that is not linked to a Session has no database representation, and lacks an identification value.

persistent

By attaching a temporary instance to a session, you can make it persistent. A persistent instance is connected to a session and has a representation in the database and an identifier value.

detached

The persistent instance will change into a detached instance once we end the Hibernate Session.

Method of Session Interface in Hibernate

1. isOpen(): This method determines whether the session is open or closed and returns a boolean value.

2. isDirty(): This method checks to see if the session has changed and returns a boolean value.

3. isConnected(): This method evaluates if the session is connected or not and returns boolean values.

4. save(Object obj): Using this technique, the primary key is generated, and the record is added to the database.

5. update(Object obj): The database record is updated using this technique.

6. saveorUpdate(Object obj): The item given determines whether this function saves or updates.

7. delete(String entity, Object obj): The persistent instance is removed using this procedure.

8. clear(): This technique terminates the session.

9get(String entity, Serializable id): The persistence status of the specified Entity is returned by this method.

10. refresh(Object obj): The entity is updated with the most recent data using this technique.

11. cancelQuery(): This technique stops the current query from running.

12. createQuery(String SQL): Query is created using this method as a new instance.

Hibernate session creation example

If the persistent classes in a session may be serialized, the session instance is serializable. The typical transaction should use the following idiom:-

Session sessions = factory.openSession();
Transaction transaction = null;

try 
{
   transaction = sessions.beginTransaction();
   // write your code here
   ...
   transaction.commit();
}
catch (Exception e) 
{
   if (transaction !=null)
{
 transaction.rollback();
}
   e.printStackTrace(); 
} 
finally
 {
   sessions.close();
}

 

The transaction must roll back and delete the session if it throws an exception.

Advantages of Hibernate Session

  • Hibernate sessions adhere to the database's ACID (Atomicity, Consistency, Isolation, and Durability) properties.
  • It is database-independent; thus, it is used with any database, including MySQL and Oracle.
  • Even rudimentary comprehension of SQL should be enough to help you comprehend how it functions.
  • Because of its uniform object mapping, the code has fewer potential flaws and faults.
  • Hibernate provides hierarchical caching, which increases the effectiveness of the coding process.

Frequently Asked Questions

Is the SessionFactory object thread-safe?

Yes, SessionFactory is a thread-safe object, meaning multiple threads cannot access it simultaneously.

What is Session?

It keeps the database and the Hibernate application connected. It offers factory methods that return these instances because it is a factory for Query, Criteria, and Transaction.

Is a session object thread-safe?

Sessions are not thread-safe objects; several threads may access them at once. To put it another way, you can distribute it among threads.

Define persistent class.

Persistent classes are those whose objects are stored in a database table.

Conclusion

Congrats on finishing the blog! This blog went into great detail about hibernate sessions, including its approach, benefits, and creation.

If you want to explore more blogs on this topic, please follow these blogs especially curated for readers like you - JDBCJDBC ConnectionGuide to ORMSpring Boot JDBC.

Please refer to our guided pathways on Code studio to learn more about DSACompetitive ProgrammingJavaScriptSystem Design, etc. Enroll in our courses, and use the accessible sample exams and questions as a guide. For placement preparations, look at the interview experiences and interview package.

Please do upvote our blogs if you find them helpful and informative!

Happy learning!

Live masterclass