Monday, November 12, 2018

Hibernate - Introduction

Greetings!

Problem in hand

Almost all the applications need to save data. This persistence storage most probably is a database. This storage is independence system which is called data independence. Here comes the problem. How do we convert relational data to Java objects? Sure we can convert one by one which is not convenient due to;
  • It takes lot of time to write code.
  • Difficult to maintain.
  • Need to write all SQL queries.
  • Need to handle transactions.
  • Have to maintain database connections.
  • Not portable.
To solve these kind of problems, Object Relational Mapping frameworks are born. Hibernate is the most popular among them.

In an era of Spring dominating most part of the application, Hibernate is almost hidden. Thanks to Spring Data most of the time we do not have write any SQL query. Spring help us to generate those.

JPA, Hibernate, Spring Data JPA

Java Persistence API is the specification. Hibernate is one of the implementations of JPA. Spring Data provides us another layer to hide JPA by giving magical interfaces to generate SQL.

Don't we have to learn SQL then?

Without knowing anything about SQL, still we can connect to database and save data, read them, etc. Working with databases is a complex topic and difficult to remember. But to get maximum from ORM framework we better know queries, how to optimize them, and so on. Unless we will end up poorly performing system. For an example, for a data set which we can select using single query, hibernate will generate multiple queries which is the famous N+1 problem.

As I mentioned earlier, we do not have to learn all the things about Hibernate either. Practically we are not going to use Hibernate along. Most of the time we are using Spring. We only have to mark our class as a database entity. Spring simplifies datasource management, transaction management, SQL generation for us.

What is important is, we need to learn Hibernate and JPA to map entities.

Hibernate ORM is an object relational mapping tool for Java.



No comments:

Post a Comment