A quick and practical guide to Hibernate’s Session object states.

1. Introduction

Hibernate is a convenient framework for managing persistent data, but understanding how it works internally can be tricky at times.

In this tutorial, we’ll learn about object states and how to move between them. We’ll also look at the problems we can encounter with detached entities and how to solve them.

2. Hibernate’s Session

The Session interface is the main tool used to communicate with Hibernate. It provides an API enabling us to create, read, update, and delete persistent objects. The session has a simple lifecycle. We open it, perform some operations, and then close it.

When we operate on the objects during the session, they get attached to that session. The changes we make are detected and saved upon closing. After closing, Hibernate breaks the connections between the objects and the session.

3. Object States

In the context of Hibernate’s Session, objects can be in one of three possible states: transient, persistent, or detached.

3.1. Transient

An object we haven’t attached to any session is in the transient state. Since it was never persisted, it doesn’t have any representation in the database. Because no session is aware of it, it won’t be saved automatically.

Let’s create a user object with the constructor and confirm that it isn’t managed by the session:

Session session = openSession();
    UserEntity userEntity = new UserEntity("John");
    assertThat(session.contains(userEntity)).isFalse();

3.2. Persistent

An object that we’ve associated with a session is in the persistent state. We either saved it or read it from a persistence context, so it represents some row in the database.

Let’s create an object and then use the persist method to make it persistent:

Session session = openSession();
    UserEntity userEntity = new UserEntity("John");
    session.persist(userEntity);
    assertThat(session.contains(userEntity)).isTrue();

Alternatively, we may use the save method. The difference is that the persist method will just save an object, and the save method will additionally generate its identifier if that’s needed.

3.3. Detached

When we close the session, all objects inside it become detached. Although they still represent rows in the database, they’re no longer managed by any session:

session.persist(userEntity);
    session.close();
    assertThat(session.isOpen()).isFalse();
    assertThatThrownBy(() -> session.contains(userEntity));

Next, we’ll learn how to save transient and detached entities

#hibernate #java #programming #developer

Object States in Hibernate's Session
1.75 GEEK