Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Transactions and Session | Fundamentals of Hibernate
Java Data Manipulation with Hibernate
course content

Course Content

Java Data Manipulation with Hibernate

Java Data Manipulation with Hibernate

1. JDBC Overview
2. Fundamentals of Hibernate
3. Final Touches

book
Transactions and Session

Currently, in our project, we have created 2 entity classes. However, this is not enough to fully interact with the database. This chapter will explore the core Hibernate interfaces that will allow us to interact with entity classes and the database effectively.

SessionFactory

Every process in Hibernate has its lifecycle. The lifecycle of a Session object is one of the most important and critical aspects.

From the definition, it can be understood that interaction with the database occurs within the scope of a single session. Here's a simplified explanation:

To start interacting with the database, we need to schedule an appointment (open a session) with a therapist named Hibernate (the framework). But before scheduling the session, the therapist needs to graduate from medical school.

In code, the analogy is the SessionFactory object, which, as the name suggests, serves as a factory for creating sessions.

Let's look at the definition:

It's quite simple: the SessionFactory interface is used to create and store instances of the Session interface.

Here's how the SessionFactory object is created in code using our two entity classes as an example:

In the configure() method, we specify the file that contains the Hibernate configuration. Using the addAnnotatedClass() method, we indicate which classes are entities. Finally, with the buildSessionFactory() method, we obtain the SessionFactory object.

You might ask: "But what if we have 100 entity classes? Will we have to specify each one in the addAnnotatedClass() method?"

Answer: Yes and no. We can move this part of the code to the configuration class by specifying all entity classes in the body of <session-factory>.

Here's how it will look:

Now we can get rid of unnecessary methods when creating the SessionFactory object:

Now, from the created SessionFactory object, we can open a session in which we will perform the necessary operations:

Transaction

All data operations must be performed within the context of a transaction. A transaction in Hibernate ensures data consistency and integrity. The developer is responsible for initiating and completing transactions.

Let's look at the definition:

Note

A transaction is a logical unit of work that includes one or more operations on the database. An operation is a specific action performed on data in the database: create, read, update, delete, and so on.

Transaction handling should be done within a try-catch-finally block because transaction operations can throw exceptions that may adversely affect the data in the table. Therefore, we need to safeguard ourselves and, in case of an error, roll back the changes to the table.

Here are the main methods for working with transactions:

  • begin() starts a new transaction. All subsequent operations will occur within this transaction;
  • commit() commits the transaction, saving all changes made during the transaction. After the commit, the changes are reflected in the database;
  • rollback() rolls back all changes made during the transaction if an error occurs.

So let's summarize and understand the algorithm:

  • Using the SessionFactory object, we create an instance of the Session interface;
  • After that, within the session, we create a Transaction object, within which we will perform operations on the database;
  • These operations will not be reflected in the database until the commit() method is used. In case of an error, we need to roll back all changes using the rollback() method;
  • Transaction operations are performed within a try-catch-finally block.

Let's look at such an implementation in the code:

Here's the template that will be used practically for every database operation.

Creating SessionFactory -> Creating Session -> Opening Transaction -> database operations -> the commit() method, which confirms the changes -> closing SessionFactory.

Now, let's take a look at the methods for working with the database.

Data Manipulation

Let's consider the main methods of the Session interface for data manipulation in Hibernate.

Note

Currently, we'll examine the methods as provided by Hibernate. Later on, we'll be using these methods as a basis to write our own methods for performing CRUD operations. Additionally, we'll develop more convenient and specialized methods (such as getEmployeesByName() and so on). This is where the most interesting logic development of the application begins, which I personally love about Java.

Let's start with the methods for saving and updating:

  • persist(Object entity): Saves the object to the database. This method should be used when you want to save a new instance of an object;
  • merge(Object entity): Updates an existing object in the database or saves it if it doesn't exist. Returns the object, which may have been modified as a result of the merge.

In code, it will look like this:

In the code above, we created a new object of the Department entity class and saved it to the database. Now, we are interested in checking if this object has been saved.

To do this, we use methods to read data from the table:

  • get(Class<T> entityClass, Object id): Retrieves an object by its identifier. Returns null if the object is not found;
  • refresh(Object entity): Updates the state of the object with data from the database, overwriting any changes made to the object.

Note

In Hibernate, there is no basic method to retrieve all elements or a specific element. With Hibernate, we can only retrieve elements by their ID. Later on, we'll write methods to retrieve all objects or specific objects from the table.

Let's see the implementation in the code:

Now, let's talk about delete operations. In Hibernate, there is also a core method for deleting an element, not by ID, but entirely as an entity. Deletion by ID and other cases will be covered later in this course.

  • delete(Object entity): Deletes the object from the database.

These are the main methods we will be using at the moment. As we encounter new methods that we need (for example, createQuery()), we will explore them in practice.

1. What is the primary function of the SessionFactory in Hibernate?
2. How is a new transaction initiated in Hibernate?
3. Which method is used to save a new instance of an object in the database?
4. Which method allows you to retrieve an object by its identifier from the database?
5. What should be done to rollback all changes made during a transaction in case of an error?
What is the primary function of the SessionFactory in Hibernate?

What is the primary function of the SessionFactory in Hibernate?

Select the correct answer

How is a new transaction initiated in Hibernate?

How is a new transaction initiated in Hibernate?

Select the correct answer

Which method is used to save a new instance of an object in the database?

Which method is used to save a new instance of an object in the database?

Select the correct answer

Which method allows you to retrieve an object by its identifier from the database?

Which method allows you to retrieve an object by its identifier from the database?

Select the correct answer

What should be done to rollback all changes made during a transaction in case of an error?

What should be done to rollback all changes made during a transaction in case of an error?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 4
We're sorry to hear that something went wrong. What happened?
some-alt