RoadToWebDev Day#10 — Understanding ORM and using Hibernate to interact with Database

Radhika Sheth
6 min readOct 28, 2020

This is a part of my ongoing series about exploring the Road To Web Development, you can find rest of the blogs here

What is Java ORM?

ORM(Object Relational Mapping) is mapping the java objects to the relational database tables and vice-versa. The ORM layer converts Java classes and objects so that they can be stored and managed in a relational database.

ORM helps to achieve the persistence of your application. Achieving the persistence of the java application conveys that the application data outlives or survives the application process.

What is JPA?

The Java Persistence API(JPA) is basically a possible approach to java ORM(Object Relational Mapping). It helps a developer to map, store, update, retrieve, access, and manage the java objects in the relational database.

It is not a tool or a framework, it is rather just a specification, a set of interfaces that needs to be implemented in order to perform java persistence.

It allows the user to access or work directly with the java objects without using SQL statements. These database operations can be performed correctly with the help of persistence metadata(defined via annotations in java class).

JPA dynamically generates queries from queries methods name.

Why JPA?

The main advantage of JPA over JDBC (the older Java API for interacting with databases) is that in JPA data is represented by classes and objects rather than by tables and records as in JDBC.

JPA is simpler, cleaner, and needs less labor than JDBC, SQL, and hand-written mapping.

It uses POJO(Plain Old Java Object) to represent persistent data that simplifies database programming.

Popular implementations of JPA are Hibernate, EclipseLink, and Apache OpenJPA, of which, we will discuss Hibernate in this article.

Hibernate:

A Hibernate is a Java framework that is used to store the Java objects in the relational database system. It is an open-source, lightweight, ORM (Object Relational Mapping) tool.

It is one of the most frequently used JPA implementation.

Why Hibernate?

Provides simple APIs for storing and retrieving Java objects directly to and from the database. It takes care of mapping Java classes to database tables using annotations without writing any custom code.

Hibernate is database independent. It can be used to connect with any database like Oracle, MySQL, Sybase, and DB2 to name a few.

Hibernate Annotations:

Hibernate Annotations is a powerful way to provide the metadata for the Object and Relational Table mapping.

These Annotations are based on the JPA 2 specification and support all the features.

All the JPA annotations are defined in the javax.persistence package. Hibernate EntityManager implements the interfaces and life cycle defined by the JPA specification.

The core advantage of using hibernate annotation is that you don’t need to create a mapping file. Here, hibernate annotations are used to provide the metadata.

We will get to know some of the hibernate annotations such as @Entity, @Table, @Id, and many more, further in this article.

Let us start with the application of the above-mentioned concepts.

We will code a project that would store and display some content of the song provided by the user.

Adding required dependencies in pom.xml file:

Here spring-boot-starter-data-jpa dependency will be required in order to connect the Spring Boot application with the relational database efficiently. The spring-boot-starter-data-jpa internally uses spring-boot-jpa dependency.

<dependency>    
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>

As we are using Hibernate, we do not need to create a database table.

There are two possible ways to apply changes to the database based on the Java classes. Add either of the following in your application.properties depending on the use-case:

  1. create: creates the schema, destroying previous data.
spring.jpa.hibernate.ddl-auto=create

2. update: updates the schema.

spring.jpa.hibernate.ddl-auto=update

Here I have used the later one.

Let us define a simple entity (Song) :

In order to implement the hibernate annotations, we need to import the javax.persistence package.

The javax.persistence package contains the classes and interfaces that define the contracts between a persistence provider and the managed classes and the clients of the Java Persistence API. Java Persistence is the API for the management of persistence and object/relational mapping.

Moving further with knowing why to use certain annotations.

@Entity annotation defines that a certain class can be mapped to a table. @Entity notation marks the Song class as an Entity bean.

The @Table annotation allows you to specify the details of the table that will be used to persist the entity in the database.

Now for any Entity, it is compulsory to add a primary key and by default, the @Id annotation will automatically determine the most appropriate primary key generation strategy to be used.

The @GeneratedValue annotation is used to specify how the primary key should be generated. Here we are using an Identity strategy which indicates that the persistence provider must assign primary keys for the entity using a database identity column.

The @Column annotation is used to specify the details of the column to which a field or property will be mapped. The name attribute permits the name of the column to be explicitly specified.

Creating a SongRepository:

Spring Boot Data enables JPA repository support by default. CrudRepository provides generic CRUD ( Create, Read, Update, Delete) operations on a repository for a specific type. CrudRepository is a Spring data interface and to use it we need to create our interface by extending CrudRepository. Spring provides CrudRepository implementation class automatically at runtime. It contains methods such as save, findById, delete, count, etc. Spring boot automatically detects our repository if the package of that repository interface is the same or sub-package of the class annotated with @SpringBootApplication.

Creating a Service Class:

In order to indicate a class as a service class or the class which consists of the main business logic, @Service annotation is used.

We saw that we can directly use methods such as save, findAll by extending the CrudRepository. Hence we will just use the object of our repository class in order to perform all the required operations with minimum lines of code.

Now run the program and making sure everything works properly as before, we can send the requests through the browser or Postman.

Pass the GET request and set the path as http://localhost:8080/song/, and Send!

We got an empty list, as we have not entered any data in the database. So, let us start appending data.
For entering only one Song object: Select POST Method-> set the path as http://localhost:8080/song/,-> go to Body-> raw; and enter the required data and Send!

Let us try appending a whole list of Song objects. For that:
Set the path to http://localhost:8080/songs/, set the specifications for passing POST request (as mentioned above), and Send.

Let us again pass the GET method and check whether both the post method worked correctly or not.

--

--