Skip to content

Hibernate Session and SessionFactory

Imagine you're building a house. You start with a blueprint (your code), gather materials (data), and then start putting it all together. Now, let's relate this to programming. In the world of Java and databases, Hibernate is like the magic wand that helps you effortlessly connect your Java objects to your database tables.

At the heart of this magic are two key players: the Hibernate Session and the SessionFactory. Think of the SessionFactory as your master architect and the Session as the construction worker who actually gets things done.

The SessionFactory is like your blueprint—it holds all the instructions on how to build and interact with your database. It's your go-to for creating sessions, which are like temporary workspaces where you can play with your data. Just like a construction worker needs a blueprint to know what to do, a session needs a SessionFactory to know how to interact with the database.

Now, imagine you're the construction worker. You grab your tools (Hibernate Session) and head to the site (your database). With your tools in hand, you can fetch data, save new information, or make changes—all within the safe confines of your session. And once you're done with your tasks, you clean up and return your tools to the toolbox (close the session).

java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Main {
    public static void main(String[] args) {
        // Set up Hibernate configuration
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");

        // Create a SessionFactory based on the configuration
        SessionFactory sessionFactory = configuration.buildSessionFactory();

        // Open a new session
        Session session = sessionFactory.openSession();

        try {
            // Begin a transaction
            session.beginTransaction();

            // Create a new object to save in the database
            Employee employee = new Employee();
            employee.setName("John Doe");
            employee.setDepartment("IT");
            employee.setSalary(50000);

            // Save the object to the database
            session.save(employee);

            // Commit the transaction
            session.getTransaction().commit();

            // Fetch the saved object from the database
            Employee retrievedEmployee = session.get(Employee.class, employee.getId());
            System.out.println("Retrieved employee: " + retrievedEmployee);

        } catch (Exception e) {
            // Roll back the transaction if an exception occurs
            session.getTransaction().rollback();
            e.printStackTrace();
        } finally {
            // Close the session
            session.close();
            // Close the session factory
            sessionFactory.close();
        }
    }
}

In this example, we first configure Hibernate using a hibernate.cfg.xml file. Then, we build a SessionFactory based on this configuration. Next, we open a Session, which serves as our workspace for interacting with the database.

Inside the session, we begin a transaction, create a new Employee object, save it to the database, and commit the transaction. We also demonstrate retrieving the saved employee from the database.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.