Object Relational Mapping(ORM) in Java

Object Relational Mapping(ORM) in Java thumbnail
32K
By Dhiraj 23 February, 2017

This article provides an insight of Object Relational Mapping. Starting from what is ORM, we will deep dive into its different concepts, facts to different ORM tools available, especially Hibernate in java, evolution from plain JDBC to ORM tool and how ORM tools have made developers life easy while dealing with tabular data format.

What is ORM

object relational mapping

Java is an object oriented programming language which is represented as a graph of objects whereas relational database is represented in a tabular format using rows and columns. So, when it comes to save an object in a database, there exist some obvious mismatch and to handle this mismatch we have Object Relational Mapping(ORM). Hence, ORM can be defined as a framework used to map an object to a relational database.

As we know, in any relational database, the top level element is table and each table is divided into rows and columns. A column contains values of a particular type and a row contains one set of data for a paticular table. For example we can say, if the table name is Employees, then name, age, address can be its different columns whereas the complete info of one single employee is maintained in a single row.

In java, the top level element is an object of a class. A class has its name similar to table name, it has some attributes defined(private or public) similar to column names in a table.

We can conclude that one plain object is equivalent to a single row in a relational database table and these are the main parameters that maps an object in java to a table in a database.

 Other Interesting Posts
Spring Hibernate Integration Example with JavaConfig
Hibernate Different Annotations Example
Hibernate One to Many Mapping Example
Hibernate One to Many Relationship Example

Why ORM is Required

As we know, java provides an API called Java Database Connectivity (JDBC) to access database. It provides ways to query a relational database. You write some native sql queries and and ask JDBC to execute those queries and underlying driver class returns you the resultset after executing it. This resultset contains multiple rows and we extract each columns of the rows using methods available based on the type of data whether its a String or Integer. Doing so a developer has to keep in mind the database table relations to write queries, the exact column names and the datatypes.

Whereas while dealing with the same data in Java, the scenario completely changes. You will encounter abstraction, inheritance, composition, identity and many more and converting the table format data to an object often leads to mismatch. The solution to this mismatch is using ORM.

As we know, there are different types of database. Each database have some of its custom functions and datatypes defined and while using JDBC we also need to care of those functions and datatypes. Apart from these, there are many others which we will be discussing in the next sections.

JDBC and ORM Comparison

Apart from the different mismatch we discussed above, there are many overheads while using JDBC. Following is a sample code to fetch employee list from database using plain JDBC.

public List getEmployees() {
	try {
		Class.forName("com.mysql.jdbc.Driver");
	} catch (ClassNotFoundException e) {
		e.printStackTrace();
	}
	Connection connection = null;
	try {
		connection = DriverManager.getConnection(
				"jdbc:mysql://localhost:3306/devglan", "root", "root");
		Statement stmt = null;
		stmt = connection.createStatement();
		ResultSet rs = null;
		if (stmt != null) {
			rs = stmt.executeQuery("select * from employees");
		}
		while (rs.next())
			System.out.println(rs.getInt(1) + "  " + rs.getString(2) + "  " + rs.getString(3));
		connection.close();
	} catch (SQLException e) {
		e.printStackTrace();
	}

}

In the above code, check the exception handling codes. Everytime it is required to close the connection and if we miss it, which is obvious sometimes, you know the consequences. Also the database configurations, e.g. url, username, password everything is mixed in a single method. Though there are some design patterns available with which we can reduce the complexity but what if someone else do these jobs for you.

To fetch same employee list using any ORM tool you only have to write following few lines:

Session session = sessionFactory.openSession();
(List<Employee>)session.createSQLQuery("SELECT * FROM Employee").addEntity(Employee.class).list();

While using ORM, you do not even require to design the db especially. You design your object graph and ORM tool will take care of others.

Also, while querying, define your query based on the object model instead of verifying and reverifying your databse table relations, datatypes, column names etc. You dont have to bother about the underlying database type whether you are connecting to Oracle or mysql.

ORM uses JDBC under the hood to connect to a database. It only has a wrapper on top of JDBC just to ease developers coding efforts and remove boiler plate codes while dealing with relational database. There are many applications which still uses plain JDBC for better performance, security and reliability.

What is JPA

JPA(Java Persistence API) is a specification that provides guidelines to implement an ORM tool, like Hibernate. It is only a specification and can not provide any concrete functionality

to your application. Its only purpose is to provide a set of rules and guidelines that can be followed by JPA implementation vendors such as Hbernate, iBATIS, Eclipse link etc. to create an ORM implementation in a standardized manner.

Different ORM Tools

There are many ORM tools available like iBATIS, Hibernate, Open JPA. Among all these tools, Hibernate is the most widely used ORM tool. This is the tool which existed before the existence of JPA. It has many additional features apart from defined by JPA. But it completely depends on individual what tool to use. All the tools have their own advantages and shortcomings.

Hibernate is the most widely used ORM framework. It is a very stable framework and possess many extra capabilities than other ORM tools available. In Feb 2017, Hibernate ORM 5.2.8 Final was released. In next article we will see how to configure hibernate projects and start working with it.

Conclusion

I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.

Further Reading on Hibernate