Recently we used JdbcTemplate in one of our projects. I tend to use Hibernate which is an ORM, whenever we need to work with databases. But lets have a short comparison between different options a java developer has for working with databases.
1. Java Database Connectivity (JDBC)
At first we can focus on the most basic alternative which is Java Database Connectivity (JDBC). JDBC is a standard java API for accessing data between the Java Standard Edition and a wide range of databases.
In short we can say JDBC API tasks are:
make and handle connections to database
creating SQL statements
executing SQL statements in target database
viewing and modifying resulting records
In most cases JDBC programming is a pain for developers as they need to manage primary things such as connections with repeating some basic codes.
2. Hibernate (ORM)
Hibernate object relational mapping provides a framework for mapping an object-oriented domain model to a relational database. So developer can focus only on the domain model and deliver all database related concerns into Hibernate. For example you can define a POJO class and relate it into a database table, instantiate an object from your class and tell Hibernate to save that object into the database table.
That's great as Hibernate handles almost all JDBC tasks itself.
But what if you need to work with database schema.
3. JdbcTemplate vs Hibernate-and-JDBC
It would be necessary in some situations to work with schema directly. For example you need to read data from a table which don't know its structure. JDBC can be a pain and also Hibernate tries to hide database concepts and elements. So Spring introduces JdbcTemplate which uses JDBC internally and provides a more facilitated API.
By JdbcTemplate we achieve the power of JDBC but no need for write boiler plate code.
The Spring JdbcTemplate has following advantages over standard JDBC:
JdbcTemplate has mechanism to clean-up resources automatically i.e. releasing the database connections
JdbcTemplate converts Jdbc SQLExceptions into RuntimeExceptions which allows the programmer to react more flexible to the errors
JdbcTemplate converts the vendor specific error messages into more understandable and unified set of error messages
JdbcTemplate provides methods to write the SQL queries directly