Advanced Java (Module 5)
Advanced Java (Module 5)
Advanced Java
Module 5
1|Page
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra 400604
Developed by:- Prof Abhay More
---------------------------------------------------------------------------------------------
JDBC Data Access with Spring :
Managing JDBC Connection, Configuring Data Source to obtain JDbC Connection, Data
Access Operations with Jdbc Template and Spring, RDBMS operation classes, Modelling JDBC
operations as Java Objects
Self learning topics: JDBC Architecture and basic JDBC Program using DML operaion
--------------------------------------------------------------------------------------------------------
Introduction
While working with the database using plain old JDBC, it becomes cumbersome to write
unnecessary code to handle exceptions, opening and closing database connections, etc.
However, Spring JDBC Framework takes care of all the low-level details starting from opening
the connection, prepare and execute the SQL statement, process exceptions, handle
transactions and finally close the connection.
So what you have to do is just define the connection parameters and specify the SQL statement
to be executed and do the required work for each iteration while fetching data from the
database.
Spring JDBC provides several approaches and correspondingly different classes to interface
with the database. I'm going to take classic and the most popular approach which makes use
of JdbcTemplate class of the framework. This is the central framework class that manages all
the database communication and exception handling.
JdbcTemplate Class
The JDBC Template class executes SQL queries, updates statements, stores procedure calls,
performs iteration over ResultSets, and extracts returned parameter values. It also catches
JDBC exceptions and translates them to the generic, more informative, exception hierarchy
defined in the org.springframework.dao package.
Instances of the JdbcTemplate class are threadsafe once configured. So you can configure a
single instance of a JdbcTemplate and then safely inject this shared reference into multiple
DAOs.
A common practice when using the JDBC Template class is to configure a DataSource in your
Spring configuration file, and then dependency-inject that shared DataSource bean into your
DAO classes, and the JdbcTemplate is created in the setter for the DataSource.
2|Page
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra 400604
Developed by:- Prof Abhay More
public int update(String query) : is used to insert, update and delete records.
public int update(String query,Object... args) : is used to insert, update and delete records
using PreparedStatement using given arguments.
public List query(String sql, RowMapper rse): is used to fetch records using RowMapper.
Create a project and create a package under the src folder in the created project.
Add required Spring libraries using Add External JARs option.
Add Spring JDBC specific latest libraries mysql-connector-java.jar,
org.springframework.jdbc.jar and org.springframework.transaction.jar in the project.
You can download required libraries if you do not have them already.
Create DAO interface and list down all the required methods. Though it is not required
and you can directly write JDBCTemplate class, but as a good practice, let's do it.
Create other required Java classes
o Class Representing table containing member variables and getter setter methods
o Create a Mapper Class which implements RowMapper interface. The
org.springframework.jdbc.core.RowMapper<T> interface is used by JdbcTemplate
for mapping rows of a ResultSet on a per-row basis. Implementations of this
interface perform the actual work of mapping each row to a result object.
SQLExceptions if any thrown will be caught and handled by the calling
JdbcTemplate.
o Create JDBCTemplate which implement DAO interface and override methods for
implementing database operation
Create xml file which holds configuration of datasource i.e. database connection setting
as well as JDBCTemplate bean and other bean configuration
Create Main class which Test working of application
3|Page
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra 400604
Developed by:- Prof Abhay More
Configuring Data Source
Let us create a database table Student in our database TEST. We assume you are working
with MySQL database, if you work with any other database then you can change your DDL
and SQL queries accordingly.
<bean id = "dataSource"
class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
<property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/>
<property name = "username" value = "root"/>
<property name = "password" value = "password"/>
</bean>
DAO stands for Data Access Object, which is commonly used for database interaction. DAOs
exist to provide a means to read and write data to the database and they should expose this
functionality through an interface by which the rest of the application will access them.
The DAO support in Spring makes it easy to work with data access technologies like JDBC,
Hibernate, JPA, or JDO in a consistent way.
Let us see how we can perform CRUD (Create, Read, Update and Delete) operation on
database tables using SQL and JDBC Template object.
4|Page
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra 400604
Developed by:- Prof Abhay More
Querying for an integer
return student;
}
}
return student;
}
}
String SQL = "insert into Student (name, age) values (?, ?)";
jdbcTemplateObject.update( SQL, new Object[]{"Zara", 11} );
Updating a row into the table
jdbcTemplateObject.execute( SQL );
6|Page
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra 400604
Developed by:- Prof Abhay More
Sample Application Which Demonstrate Basic JDBC Program using DML operation Spring
We are using MySql backend with database IMCOST and Student table with following
structure
CREATE TABLE Student(
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
PRIMARY KEY (ID)
);
Following is the content of the Data Access Object interface file StudentDAO.java
import java.util.List;
import javax.sql.DataSource;
// This is the method to be used to list down a record from the Student table
// corresponding to a passed student id.
//This is the method to be used to list down all the records from the Student table.
//This is the method to be used to delete a record from the Student table
//corresponding to a passed student id.
//This is the method to be used to update a record into the Student table.
7|Page
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra 400604
Developed by:- Prof Abhay More
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
return student;
}
}
8|Page
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra 400604
Developed by:- Prof Abhay More
Following is the implementation class file StudentJDBCTemplate.java for the defined
DAO interface StudentDAO.
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
return student;
}
public List<Student> listStudents() {
String SQL = "select * from Student";
List <Student> students = jdbcTemplateObject.query(SQL, new
StudentMapper());
return students;
}
public void delete(Integer id) {
String SQL = "delete from Student where id = ?";
jdbcTemplateObject.update(SQL, id);
System.out.println("Deleted Record with ID = " + id );
return;
}
9|Page
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra 400604
Developed by:- Prof Abhay More
public void update(Integer id, Integer age){
String SQL = "update Student set age = ? where id = ?";
jdbcTemplateObject.update(SQL, age, id);
System.out.println("Updated Record with ID = " + id );
return;
}
}
</beans>
10 | P a g e
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra 400604
Developed by:- Prof Abhay More
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tutorialspoint.StudentJDBCTemplate;
StudentJDBCTemplate studentJDBCTemplate =
(StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
System.out.println("------Records Creation--------" );
studentJDBCTemplate.create("Zara", 11);
studentJDBCTemplate.create("Nuha", 2);
studentJDBCTemplate.create("Ayan", 15);
11 | P a g e