One of the most popular and powerful tools to connect to the database and execute SQL queries, the Spring JDBC template is just made to simplify the JDBC applications of the Spring framework. It helps to eradicate a lot of problems with the JDBC Application programming interface (API) by using the JDBC API internally. JDBC template works as a backbone of the core JDBC workflow and helps eliminate common errors. Its application code is used to provide SQL (Structured Query Language) and extract results from it. The central class that comes in the JDBC core package is The org.spring framework.jdbc.core.JdbcTemplate class.
Before we further delve into the concept of the JDBC template in the Spring framework, we should know that the JDBC is divided into four different packages, that are:
This is the core functionality of the JDBC. The core package of the JDBC template includes some useful and important classes, which are JdbcTemplate, SimpleJdbcInsert, SimpleJdbcCall, and NamedParameterJdbcTemplate.
These are the utility classes that are used to access a data source. It has several data source implementations for testing JDBC code in the Jakarta EE container externally. It is always to be noted that a datasource should be configured as a bean in the application context.
It allows database access in an object-oriented style. By using objects, we are able to run queries and return the results as a business object. It provides the functionality to map the query results between the columns and properties of business objects.
This package of JDBC supports classes for classes under core and object packages. For example, it provides the functionality of SQLException translation.
There are four approaches that are supported by the Spring framework for JDBC database access that is:
But in this tutorial, we will study the usage of the JDBC template to access the database.
Defined as the central class in the JDBC core package, JdbcTemplate class is responsible for the creation and release of resources like creating and closing of the connection object, etc; The interesting thing in this is that there will not be any problem that can occur in case you forget to close the connection. It takes care of the exception and provides the informative exception messages through exception classes defined in the org.springframework.dao package.
JdbcTemplate class provides all the database operations ranging from insertion, update, deletion to retrieval of the data from the database. Its code only needs to implement callback interfaces. The parameters of this class include callback interfaces and the SQLExceptionTranslator interface that results in the removal of the requirement to subclass it. The entire SQL operations in the JdbcTemplate class are logged at debug level by the log category that is defined as "org.springframework.jdbc.core.JdbcTemplate".
This method is used to insert, update and delete records in a relational database.
This method is used to insert, update and delete records using PreparedStatement using given arguments.
This method is used to execute Data Definition Language (DDL).
This method is used to execute the query by using PreparedStatement callback.
This method is used to retrieve records using ResultSetExtractor.
Here in this method, RowMapper is used to fetch records.
Let’s better understand the above methods by an example that uses the JDBC template class. We have just created a table inside the Oracle10g database.
create table employee( id number(10), name varchar2(100), salary number(10) );
Now we will create a class named Employee.java that includes three properties with constructors and their setters and getters.
package com.Intellinuts; public class Employee { private int id; private String name; private float salary; //no-arg and parameterized constructors //getters and setters }
Going further, we create a class named EmployeeDao.java that includes one property jdbcTemplate, and three methods that are saveEmployee(), updateEmployee, and deleteEmployee().
package com.Intellinuts; import org.springframework.jdbc.core.JdbcTemplate; public class EmployeeDao { private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public int saveEmployee(Employee e){ String query="insert into employee values( '"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')"; return jdbcTemplate.update(query); } public int updateEmployee(Employee e){ String query="update employee set name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' "; return jdbcTemplate.update(query); } public int deleteEmployee(Employee e){ String query="delete from employee where id='"+e.getId()+"' "; return jdbcTemplate.update(query); } }
Now we will create the XML configuration file named applicationContext.xml that stores the bean information.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" /> <property name="username" value="system" /> <property name="password" value="oracle" /> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="ds"></property> </bean> <bean id="edao" class="com.Intellinuts.EmployeeDao"> <property name="jdbcTemplate" ref="jdbcTemplate"></property> </bean> </beans>
In the above file, there is a property named datasource in the JdbcTemplate class of the DriverManagerDataSource type. Here the JdbcTemplate class will need the reference from the DriverManagerDataSource object for the datasource property.
In the EmployeeDao class, we are using the JdbcTemplate object that is passed by the setter method, but the same can be done by the constructor also.
Now we will create a class named Test.java that will execute the query by getting the bean information from the applicationContext.xml file, and calling the saveEmployee() method. You can also execute the query by calling the updateEmployee() and deleteEmployee() method by uncommenting the code.
package com.Intellinuts; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); EmployeeDao dao=(EmployeeDao)ctx.getBean("edao"); int status=dao.saveEmployee(new Employee(102,"Amit",35000)); System.out.println(status); /*int status=dao.updateEmployee(new Employee(102,"Sonoo",15000)); System.out.println(status); */ /*Employee e=new Employee(); e.setId(102); int status=dao.deleteEmployee(e); System.out.println(status);*/ } }