Let’s understand what is better to use JDBC or ORM.
The Java Database Connectivity is a free open-source application programming interface. It is a standard Java API specifying interfaces for connectivity between the Java applications and a wide range of databases. The JDBC contains methods to connect to a database server, send queries to create a table, update, delete, insert records in a database, retrieve and process the results obtained from a database. Nowadays, there are a lot of frameworks that are built for easier work with databases. But they contain the JDBC under the hood.
Let’s look at the JDBC Workflow. Initially, we need to open a database connection with the help of a JDBC driver. After the connection is established, we can send SQL queries to a database using a JDBC driver. We are executing the queries and getting the result set. In JDBC workflow the data are sent to the application via the driver manager.
When the application gets the results, it works on the processing of the data. We usually copy values from the result set to the corresponding application’s objects. Finally, we need to close the connection to the database.
If you want to work with a database via JDBC the JDBC driver will be needed. Also, every programming language requires its own specific JDBC driver. Let’s look at popular commercial and open-source databases that provide JDBC drivers for Java applications: Oracle, Microsoft SQL Server, PostgreSQL, MariaDB, Derby. There are of cause more but the listened are the most commonly used.
ORM Workflow
ORM responsible for establishing connections with the database, unlike JDBC. It uses Query Language to communicate with the database and execute the queries. After, ORM maps itself the results to corresponding Java objects. The mapping to the objects is done automatically and based on the properties from the ORM configuration XML file.
We get the database connections from an application using the session. The session also helps to save, edit, update and retrieve the persistent object.
The instance of a session is creating with Session factory interface. We usually have just one session factory per one database server or database infrastructure. For example, assuming that we use two databases MySQL and Oracle in our application. In this case, we need to create one session factory for MySQL and another one session factory for Oracle. We don’t need more than one session factory for one database alone.
All ORMs can work with databases that support them. Let’s look, as an example, at the list of databases that support Hibernate ORM: Oracle (versions 11g and 11g RAC), Microsoft SQL Server from version 2008, DB2 starting from 9.7, Sybase ASE, MySQL(5.1 and later versions), PostgreSQL from the version 8.4, Apache Derby. As you can see, the list is long, but you need to double-check before use.
Object Mapping
Let’s compare one object mapping process with JDBC and ORM.
We will take some Student class that has fields Id, name, surname, email:
public class Student { private String id; private String name; private String surname; private String email; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
For JDBC, you need to write all code for mapping your object data to a relational model. You have to perform all the copy process manually. Here is a code snippet:
List<Student> students = new ArrayList<Student>(); while(result.next()) { Student student = new Student(); student.setId(result.getString("Id")); student.setName(result.getString("Name")); student.setSurname(result.getString("Surname")); student.setEmail(result.getString(“Email”)); students.add(student); }
ORM in comparison with JDBC does all work by itself. It maps Java classes to the database tables using XML or annotations. Let’s look at the following example to understand how ORM does this. We will use code snippet written in Hibernate.
//Hibernate @Entity @Table(name = "student") public class StudentModel { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private BigInteger id; @NotEmpty @Column(name = "name") private String name; @NotEmpty @Column(name = "surname", unique = true) private String surname; @NotEmpty @Column(name = "email", unique = true) private String email; public String getId() { return id; } public void setId(BigInteger id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
JDBC Advantages and Disadvantages
JDBC is good because we usually have clean SQL processing, good performance even with large data. It is not a bad idea to use JBDC for small applications. Anyway it has a simple syntax that is easy to learn
But, with JDBC things become complex if it is used in large projects. We get a large programming overhead, no encapsulation. Implementation of the MVC concept becomes harder. One more disadvantage of JDBC is that SQL queries are DBMS specific. ORM solves all of the issues that we have with using JDBC.
ORM Advantages and Disadvantages
Let’s look at ORM technique advantages over the plain JDBC. First of all, it is designed to let the business code access objects rather than DB tables. In applications that use ORM, we hide details of SQL queries from object-oriented logic. Anyway, ORMs are based on JDBC ‘under the hood.’ Developers don’t need to deal with database implementation. Entities application turns to application based on business concepts rather than the structure of the database. With ORM we get all the transaction management and automatic key generation. Our application development is much quicker. ORMs improve the maintainability of applications. You need to write a lot less code and do not need to deal with the database implementation. ORMs improve portability because generate database-specific SQL for you, Finally, entities are more based on business concepts rather than a database structure.
There is a bunch of persistent frameworks and ORMs for Java language: Enterprise JavaBeans Entity Beans, Java Data Objects, Castor, TopLink, Spring DAO, Hibernate, etc. We will look closer at Hibernate.
ORM solution consists of four parts. They are:
- API that performs basic CRUD operations on persistent classes objects.
- language or API to create and execute queries on classes and properties of classes.
- Some configurable facilities for specifying mapping metadata.
- Possibilities to interact with transactional objects to perform optimization functions such us dirty checking, lazy association fetching, etc.
Object-Relational Mapping(ORM) technologies are responsible for saving/reading/editing/deleting the objects from our application to the relational database tables. They protect developers from work with SQL languages. Each relational database has its own standards of SQL language. Therefore, ORM makes our Java application more flexible.
All ORMs have just one main disadvantage in comparison with JDBC. They have slow performance in case of large batch updates. JDBC, in this case, will perform better. But, in general, they are just a little bit slower than Java Database Connectivity technology.
Summary
Let’s decide for ourselves when it is better to use ORM technology as compared to JDBC and vise versa.
In the case of a domain-driven application, it is better to use ORM. The same decision will be better to take in case of complex objects’ relationships. If your application is simple enough, better to use JDBC. The simple application means application just to present data directly from the database and the relationships between objects are simple enough.
But, if you decide to use JDBC be ready for some unpleasant things. As we already understood, with JDBC, the developer has to write code for mapping. We need to write a lot of lines of code because Java objects with database tables and vice versa conversion have to be done manually.
JDBC supports just native database Structured Query Language (SQL). The developer has to be familiar with it and to search for an efficient way to work on the database. For example, developers need to find out an effective query from a number of queries that can do the same action on data. Java application that uses JDBC has a large amount of database-specific code. When the table structure is changed then it will be essential to append time on changing code written to map table-to-object/object-to-table.
The developer’s responsibility is to handle the JDBC result set. If you need caching in an application that uses JDBC ou need to find out how to implement it, usually by hand-coding. The developer has to implement also code to check that every user has updated data. ORM will help you to do the mapping automatically. It is designed to let the business code access objects and not DB tables. ORMs provide all the transaction management and automatic key generation. Our application development is much quicker. ORMs improve the maintainability of applications. ORMs improve portability because generate database-specific SQL for you.
One Response
Thanks for such a detailed explanation. Really appreciate it. Can you please explain what do you mean by domain-driven application here?