Java Hibernate
Introduction
IT industry is today working on object-oriented languages with relational databases as the backbone of the application for storing and retrieving the data. The database stores a large volume of data in one single place. Along with that, databases provide us an efficient way of searching the records so that data can be found easily and quickly. But when working with the objects one thing the database does not support is the storage of objects as it stores only relational data. Data in the form of objects provide abstraction and portability.
Is there any technique through which we can directly store and retrieve objects in a relational database? The answer is yes, you can. The name of the technique is ORM.
Object Relational Mapping (ORM)
ORM solves the mismatch between the object model and the relational database. The name itself suggests the mapping of objects into relational tables. ORM technique converts objects into relational data and vice versa. Now the question arises how it is done?
Basically, the name of the instance variable is given to the column name and its value forms the row in the relational database. Now the thing is whether you need to declare a table in the database to store objects. The answer is no, ORM will do it for us by declaring data types for the columns the same as of instance variables. But for that, we need to do a small configuration to tell the ORM how the objects will be mapped. In java, ORM works on plain old java object (POJO) classes whose objects need to be mapped. These classes are nothing but consist of private instance variables, a parameterized constructor with public getters and setters.
Along with parameterized constructor, the POJO class must have a no-argument public constructor because it is needed by the ORM for serialization purposes. As parameterized constructor is present, compile will not add any argument constructor on its own therefore you have to do it manually.
What is Hibernate?
Hibernate is an open-source high-performance object-relational mapping tool for the Java programming language. It was released in 2001 by Gavin King with colleagues from Cirrus Technologies as an alternative to EJB2 style entity beans. This framework is responsible for solving object-relational impedance mismatch problems. In Java, we have a specification called Java Persistence API(JPA) that describes the management of objects in the relational database. Hibernate is just an implementation of JPA.
Hibernate Architecture
Here we will discuss the components of which hibernate is composed. Hibernate has a layered architecture that helps us to operate without knowing the underlying APIs which implement object-relational mapping. Hibernate resides between our java application and the database. The hibernate architecture is categorized into four layers.

· Java application layer
· Hibernate framework layer
· API layer
· Database layer
In the above diagram, you can see all four layers. The data flow between the java application and database is done using the hibernate-defined persistent object. The hibernate framework layer consists of various objects such as configuration, session factory, session, transaction, query, and criteria. You create these objects manually whenever needed.
Configuration object — It is the first hibernate object you create in any hibernate application. It activates the hibernate framework. The configuration object is created only once during application initialization. The configuration object is the parent object from which all the other objects are created. It checks whether the configuration file is syntactically correct or not. It represents the configuration and mapping properties required by the hibernate.
Session Factory object — A session factory is a heavy-weight thread safe object and used by multiple threads at a time. So, this object should be instantiated only once in our application and kept for later use. You need one session factory object per database. The session factory is responsible for configuring hibernate with the configuration properties supplied by the configuration object.
Session object — A session object is a lightweight object and created every time you need to interact with the database. Persistent objects are saved and retrieved through a session object. It is not a thread-safe object therefore should be destroyed after the interaction is complete.
Transaction object — It represents a unit of work with the database. It is an optional object but should be used to ensure data integrity and if any error occurs rollback can be performed.
Query object — Query object is used to write queries to perform CRUD operations in the database. We can write a query in SQL or use Hibernate Query Language (HQL). You will get to know more about HQL in the implementation.
Criteria object — It is used to execute object-oriented queries to retrieve objects from the database.
How to configure hibernate?
First, we need to install hibernate in our project. You can download a jar file or use a more convenient method i.e., maven. It will help us to download hibernate dependency defined in the POM.xml file.

If you want to know more about maven then visit the below link.
Hibernate framework needs to know how to map objects, database server credentials where objects will be stored and retrieved, and few more properties. So, now the question is how we will supply this information to hibernate.
In java, the configuration is done using an XML file. We need to provide two XML files.
· hibernate.cfg.xml which contain hibernate properties like dialect, driver class, database server URL, username, and password.
· Mapping file which contains the mapping relationship between java objects and database tables. The name of the file should be <type of an object>.hbm.XML. For example, if we want to work on an employee-type object, the filename is Employee.hbm.xml.
The XML files should be put inside the META-INF folder created in src/main/resources. The third component we need in this setup is the POJO class which we have discussed earlier.
Let’s take an example of working with flight-type objects. It has Id, flight number, departure location, arrival location, flight date, and fare as instance variables. The id will be the primary key of the table.

The above image is the hbm.cfg.xml file. You can see all the properties are defined inside the hibernate-configuration tag. Inside the session-factory tag, you define the database properties to which it needs to connect.
hbm2ddl.auto property validates or exports schema data definition language when session factory object is created. Here we have used an update that will update the database and previous data remain stored. We have a few more to work with like validate, create, and create-drop.

The above XML code is of the mapping file. All the properties are defined inside the hibernate-mapping tag. Class tag is for defining the POJO class name and table name to be created inside the database as attributes and mapping relationships as values. The primary key is defined inside the id tag. We define the name of the instance variable inside the name attribute. Column name and data type are given in column and type attributes respectively. Generator tags provide us the strategy with which we need to perform auto increment. All other instance variable mapping is provided inside property tags.
Now the time comes when we need to create a flight POJO class whose objects will persist in the table FLIGHTS. There is an empty default constructor whose need we have defined earlier.

One question in your mind is being a java programmer and using a java tool, why I need to do configuration using XML. Is there any way to eliminate XML? The answer is you can, but it can be done partially. The mapping file can be eliminated with the help of annotations, but the config file is still to be done with XML. Annotations is a powerful way to define mapping relationship between object and the relational model. It starts with @.
You just need to add annotations inside the POJO class. No separate file is needed.

The annotation should be defined just above the field declaration.
@Entity tells hibernate that this class is an entity bean, and its objects need to be persisted.
@Table used to specify the name of the table to be created in the database.
@Id is used to define the primary key. We can also add multiple fields with it to create a composite key.
@GeneratedValue defines the strategy to increment a field. It is optional, if not defined with @Id a default strategy is applied.
@Column defines how the given field is mapped to a column in a table. It takes attributes like the name of the column, column definition, nullable, unique, etc. Unlike XML files you do not need to provide type as it is taken from the field.
Implementation Of Hibernate
Finally, we will try to perform CRUD operations using hibernate. For this, let's create a class named DAO. First, we create a session factory object. There are two ways to create it. If we do not use annotation, then create like this.

Another way will be defined in the below example. The procedure to create all other objects is the same for both. The first example is to add flight objects to the database. We create an addFlight method that stores the flight object in the database. Keep the transaction work in the try-catch, so that if any issue occurs rollback can be performed otherwise commit the transaction.
Save operation
Save method in session object perform the object insertion task.

Update operation
Now let’s move ahead and try to perform an update on the exciting data in the table.

We have created the updateFlightNumber method in which we first retrieve the flight object with the given id and then updates its flight number by the setter method. After doing this we call the update method to update the existing entity.
Note: If you want to print the retrieved objects from the database on the console, add the toString() method in the POJO class otherwise hash code will be printed.
Delete operation
The database has only one object with id=1. Now we will try to delete the object present in the database.

After the deleteFlight method is executed, the table gets empty. In the above java code, we have first retrieved the object by its id and pass that object to the delete method. If all goes well transaction is committed otherwise rollback will be performed.
Now one thing we have observed whether we want to get an update or delete an object in the database we need its primary key value which is not so helpful as we do not always have a primary key value. Also, we need to perform complex operations on the data. This can be achieved by using HQL similar to SQL, but it removes boilerplate code which means we do not need to use select statements with the queries.

Let me demonstrate all the learning we have gained in the form of a short video. The below video will discuss the key topics with which we should be familiar to start our journey with hibernate.