Hibernate Basics (Part 2)

Dev_RV
8 min readMar 21, 2024

--

What is ORM : Hibernate ORM Framework ? How hibernate framework works ?

The data that needs to be persisted can be:

  • Raw data: collected from a file or any other source in the form of bytes.
  • Java object: the data contained in the object of a Java class.

Serialization helps in sending Java objects through the network and this also can be used to store these Java objects in a file.

  • An object can be marked serializable by implementing the java.io.Serializable interface.
  • Serializable objects can be converted into a stream of bytes.
  • This stream of bytes can be written into a file.
  • These bytes can be read back to re-create the object.
  • Deserialization is the process of retrieving an object from the byte streams.

Challenge of Object-Relational Impedance Mismatch

The greatest challenge in integrating the concepts of RDBMS and OOP is mapping of the Java objects to databases. When object and relational paradigms work with each other, there arises technical and conceptual difficulties arise, as mapping of an object to a table may not be possible in all the contexts.

Storing and retrieving Java objects using a Relational database exposes a paradigm mismatch called “Object-Relational Impedance Mismatch”. These differences are because of perception, style, and patterns involved in both the paradigms that leads to the following paradigm mismatches:

  • Granularity: Mismatch between the number of classes in the object model and the number of tables in the relational model.
  • Inheritance or Subtype: Inheritance is an object-oriented paradigm that is not available in RDBMS.
  • Associations: In object-oriented programming, the association is represented using reference variables, whereas, in the relational model foreign keys are used for associating two tables.
  • Identity: In Java, object equality is determined by the “==” operator or “equals()” method, whereas in RDBMS, uses the primary key to uniquely identify the records.
  • Data Navigation: In Java, the dot(.) operator is used to travel through the object network, whereas, in RDBMS join operation is used to move between related records.

Solutioning —

Resolving Object-Relational Impedance Mismatch is one of the key challenges in data persistence. Object Relational Mapping helps to achieve the same.

Following are the reason for using ORM:

  • ORM resolves the Object-Relational Paradigm mismatch.
  • The lower level interaction with the database is handled by the ORM. Framing and executing the database dependent queries is taken care of by the ORM framework.
  • ORM helps the developer to get rid of “messy SQL”. The developer need not waste time in writing the plumbing code.
  • ORM allows the developer to concentrate on the business logic and work with the object model.
  • ORM is database independent. All database vendors give the necessary support for ORM. Hence the application code becomes portable without worrying about the underlying database.
  • ORM frameworks are preferred as an elegant persistence solution for Enterprise applications. There are a lot of ORM frameworks from different vendors available in the market.

=> Available Frameworks *

Many third-party persistence frameworks like Hibernate, EclipseLink, are available in the market. These frameworks helped the developers to achieve Object Relational Mapping and perform database operations in the object-oriented approach. But it became challenging to the port application from one ORM framework to another, as every framework addressed the Object-Relational Impedance mismatch in its own way.

In 2006, Java Persistence API (JPA) was released by Java Community Process, to standardize the persistence process. JPA incorporated many features from the existing frameworks like Hibernate and TopLink Essentials.

JPA became the standard specification for ORM in Java. As the name indicates, JPA is a specification (with a set of interfaces), which provides the standards and specifications to be followed while mapping the Java objects to the database tables.

Each vendor, who provides an ORM framework, implements JPA. A few of the ORM frameworks are EclipseLink, OpenJPA, and Hibernate. Any of these ORM frameworks can be used to connect a Java application to the database.

Object Relational Mapping (ORM) , the Java entity classes are mapped to relational database tables. In this technique the entity classes are mapped to the database tables, the data members are mapped to the database table columns, and objects of Java entity classes are mapped to the records of the database tables.

Consider a Java Entity class “Account” with a mapping database table “Account” as below:-

Hibernate -

  • Hibernate provides an implementation for JPA Specification.
  • Hibernate is a powerful ORM solution that maps user-defined Java classes to DB tables.
  • Hibernate has a strong query language which is called Hibernate Query Language. It supports native SQL as well.
  • Hibernate reduces the number of lines in the code by keeping object-table mapping itself and gives the result to an application as Java objects. It ensures the programmer doesn’t have to manually handle persistent data, this way reducing the time of development and cost of maintenance.
  • Hibernate uses SQL based schema for mapping object model to the relational model.
  • Hibernate allows developers to emphasize the domain model and not on the persistence plumbing (e.g.: connection management).

Hibernate is a pure Java Persistence Framework that supports Object Relational Mapping. The main goal of this framework is to release the programmers from the common data persistence related works. It is an open-source framework.

  • Hibernate provides an implementation for JPA Specification.
  • Hibernate is a powerful ORM solution that maps user-defined Java classes to DB tables.
  • Hibernate has a strong query language which is called HQL. It supports native SQL as well.
  • Hibernate reduces the number of lines in the code by keeping object-table mapping itself and gives the result to an application as Java objects. It ensures the programmer doesn’t have to manually handle persistent data, this way reducing the time of development and cost of maintenance.
  • Hibernate uses SQL based schema for mapping object model to the relational model.

Features of Hibernate: following are the features of Hibernate:

  • Object Relational Mapping: Hibernate, being an ORM framework aims to resolve the Object-Relational Impedance Mismatches proving itself as an effective data persistence medium.
  • Scalability and Reliability: Hibernate works well in the client-server based environment and delivers a scalable architecture. Hibernate provides good stability and quality, hence it is reliable.
  • Extensible: Hibernate is highly configurable and extensible.
  • High Performance: Hibernate has high performance due to various features like multiple fetch strategies, optimistic locking with automatic versioning and time stamping, caching, etc.
  • Idiomatic Persistence: Hibernate enables the development of persistent classes that follows object-oriented idioms like inheritance, composition, polymorphism, association, and the Java collections framework.

Benefits of Hibernate: following are the benefits of Hibernate:

  • Lightweight: Hibernate implements ORM using simple Plane Old Java Object (POJO) classes.
  • Open Source: Hibernate is freely available and may be redistributed and modified
  • Vendor Independent: Hibernate, or in general JPA, prevents writing code according to the database vendor. Hence it is vendor-independent.
  • Non-Invasive: Hibernate does not force the developer to extend or implement any class or interface.

Note :
POJO is nothing but a normal Java class and does not implement any special interfaces of any of the Java frameworks.

Steps for a Java application in order to connect to the database using Hibernate.

CRUD (CREATE, READ, UPDATE, DELETE) operations in Hibernate means .

CREATE is used to create a record in the database table.

READ is used to read the data from the database table.

UPDATE is used for updating a database table record.

DELETE is used for deleting a database table record.

The Session API provides methods for performing the CRUD operation.

  • To CREATE/UPDATE the data, the methods available are :

save()

persist()

update()

saveOrUpdate()

  • To READ the data, the methods available are:

get()

load()

refresh()

  • To DELETE the data, the method available is:
  • delete()

Implementation of CRUD using hibernate -

Assuming Project set up is done having interface , Mapping class so now will show the DAO class

The session API methods provide various methods for performing CRUD operations on entities. There are some intricate differences between the methods. However, to decide the usage of appropriate session methods(eg: get() or load()) requires the understanding of Persistence Context and the Hibernate Entity States.

The entity state is defined with respect to its relation with the Session instance, or in other words, its proximity with the Persistence Context. As shown below an entity is in any one of the four different states: transient, persistent, detached, or removed.

A Persistence context is a cache that remembers all the modifications and state changes made to objects in a particular unit of work. The org.hibernate.Session API states a context for handling persistent data. This is called a persistence context.

Now to have unique entry we have-Identifier Generation Strategy

  1. Increment Strategy
    Increase id value by +1.

2. Identity Strategy

In Identity strategy, Hibernate uses the identity column of the underlying database. An integer column having a primary key or unique constraint with the AUTO_INCREMENT feature is known as the IDENTITY column of a table. This strategy is database dependent, for example, it works on MySQL but not in Oracle.

  • @GenericGenerator is not used for this strategy as the Hibernate depends on the underlying database to generate the value.
  • @GeneratedValue defines the strategy type as IDENTITY.

Identity strategy can auto-generate the identifier value for short, int and long data types. When there are no rows in the table, the starting value of the IDENTITY column will be 1, and it will be incremented by 1 for each new record. When the rows are already available in the table, MySQL will take the maximum value from the primary key column of the table and will add 1 to it.

3.Assigned Strategy

In some scenarios, an application may want to provide the identifier value instead of Hibernate generating it. In such cases, the “assigned” strategy can be used.

Assigned is the default strategy in Hibernate. So, if no strategy is defined for the identifier of an entity, Hibernate considers it as an assigned strategy.

https://medium.com/@dev_RV/hibernate-565fb543df99

--

--

Dev_RV

Knows about DSA , Java , Springboot , Microservices