0% found this document useful (0 votes)
66 views

Advanced Java (Module 5)

The document provides information on using the Spring framework to access and manage JDBC connections and perform database operations. It discusses using the JdbcTemplate class to execute SQL queries, updates, and stored procedures. It describes configuring a DataSource in XML to define the database connection settings. It then shows examples of using the JdbcTemplate to perform CRUD operations on a Student table, including querying for objects and lists of objects, inserting, updating, and deleting rows.

Uploaded by

Sushma Sumant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

Advanced Java (Module 5)

The document provides information on using the Spring framework to access and manage JDBC connections and perform database operations. It discusses using the JdbcTemplate class to execute SQL queries, updates, and stored procedures. It describes configuring a DataSource in XML to define the database connection settings. It then shows examples of using the JdbcTemplate to perform CRUD operations on a Student table, including querying for objects and lists of objects, inserting, updating, and deleting rows.

Uploaded by

Sushma Sumant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

C-4, Wagle Industrial Estate,

Near Mulund Check Naka,


Thane West, opp. Aplab,
Mumbai, Maharashtra 400604
Developed by:- Prof Abhay More

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

Methods of JDBCTemplate Class

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 void execute(String query) : is used to execute DDL query.

public T execute(String sql, PreparedStatementCallback action): executes the query by using


PreparedStatement callback.

public T query(String sql, ResultSetExtractor rse): is used to fetch records using


ResultSetExtractor.

public List query(String sql, RowMapper rse): is used to fetch records using RowMapper.

Steps To Create JDBC With Spring

 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.

CREATE TABLE Student(


ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
PRIMARY KEY (ID)
);
Now we need to supply a DataSource to the JDBC Template so it can configure itself to get
database access. You can configure the DataSource in the XML file with a piece of code as
shown in the following code snippet −

<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>

Data Access Object (DAO)

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.

Executing SQL statements

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

String SQL = "select count(*) from Student";


int rowCount = jdbcTemplateObject.queryForInt( SQL );
Querying for a long

String SQL = "select count(*) from Student";


long rowCount = jdbcTemplateObject.queryForLong( SQL );
A simple query using a bind variable

String SQL = "select age from Student where id = ?";


int age = jdbcTemplateObject.queryForInt(SQL, new Object[]{10});
Querying for a String

String SQL = "select name from Student where id = ?";


String name = jdbcTemplateObject.queryForObject(SQL, new Object[]{10}, String.class);
Querying and returning an object

String SQL = "select * from Student where id = ?";


Student student = jdbcTemplateObject.queryForObject(
SQL, new Object[]{10}, new StudentMapper());

public class StudentMapper implements RowMapper<Student> {


public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student student = new Student();
student.setID(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));

return student;
}
}

Querying and returning multiple objects

String SQL = "select * from Student";


List<Student> students = jdbcTemplateObject.query(
SQL, new StudentMapper());

public class StudentMapper implements RowMapper<Student> {


public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
5|Page
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra 400604
Developed by:- Prof Abhay More
Student student = new Student();
student.setID(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));

return student;
}
}

Inserting a row into the table

String SQL = "insert into Student (name, age) values (?, ?)";
jdbcTemplateObject.update( SQL, new Object[]{"Zara", 11} );
Updating a row into the table

String SQL = "update Student set name = ? where id = ?";


jdbcTemplateObject.update( SQL, new Object[]{"Zara", 10} );
Deleting a row from the table

String SQL = "delete Student where id = ?";


jdbcTemplateObject.update( SQL, new Object[]{20} );
Executing DDL Statements
You can use the execute(..) method from jdbcTemplate to execute any SQL statements or
DDL statements. Following is an example to use CREATE statement to create a table −

String SQL = "CREATE TABLE Student( " +


"ID INT NOT NULL AUTO_INCREMENT, " +
"NAME VARCHAR(20) NOT NULL, " +
"AGE INT NOT NULL, " +
"PRIMARY KEY (ID));"

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;

public interface StudentDAO {

// This is the method to be used to initialize database resources ie. connection

public void setDataSource(DataSource ds);

// This is the method to be used to create a record in the Student table.

public void create(String name, Integer age);

// This is the method to be used to list down a record from the Student table
// corresponding to a passed student id.

public Student getStudent(Integer id);

//This is the method to be used to list down all the records from the Student table.

public List<Student> listStudents();

//This is the method to be used to delete a record from the Student table
//corresponding to a passed student id.

public void delete(Integer id);

//This is the method to be used to update a record into the Student table.

public void update(Integer id, Integer age);


}

7|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 content of the Student.java file

public class Student {


private Integer age;
private String name;
private Integer id;

public void setAge(Integer age) {this.age = age; }


public Integer getAge() { return age; }
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public void setId(Integer id) { this.id = id; }
public Integer getId() { return id; }
}

 Following is the content of the StudentMapper.java file

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

public class StudentMapper implements RowMapper<Student> {


public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));

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;

public class StudentJDBCTemplate implements StudentDAO {


private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;

public void setDataSource(DataSource dataSource) {


this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public void create(String name, Integer age) {
String SQL = "insert into Student (name, age) values (?, ?)";
jdbcTemplateObject.update( SQL, name, age);
System.out.println("Created Record Name = " + name + " Age = " + age);
return;
}
public Student getStudent(Integer id) {
String SQL = "select * from Student where id = ?";
Student student = jdbcTemplateObject.queryForObject(SQL,
new Object[]{id}, new StudentMapper());

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;
}
}

 Following is the configuration file Beans.xml

<?xml version = "1.0" encoding = "UTF-8"?>


<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">

<!-- Initialization for data source -->


<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/IMCOST?useSSL=false"/>
<property name = "username" value = "root"/>
<property name = "password" value = "root"/>
</bean>

<!-- Definition for studentJDBCTemplate bean -->


<bean id = "studentJDBCTemplate"
class = "com.test.StudentJDBCTemplate">
<property name = "dataSource" ref = "dataSource" />
</bean>

</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

 Following is the content of the MainApp.java file

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tutorialspoint.StudentJDBCTemplate;

public class MainApp {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

StudentJDBCTemplate studentJDBCTemplate =
(StudentJDBCTemplate)context.getBean("studentJDBCTemplate");

System.out.println("------Records Creation--------" );
studentJDBCTemplate.create("Zara", 11);
studentJDBCTemplate.create("Nuha", 2);
studentJDBCTemplate.create("Ayan", 15);

System.out.println("------Listing Multiple Records--------" );


List<Student> students = studentJDBCTemplate.listStudents();

for (Student record : students) {


System.out.print("ID : " + record.getId() );
System.out.print(", Name : " + record.getName() );
System.out.println(", Age : " + record.getAge());
}

System.out.println("----Updating Record with ID = 2 -----" );


studentJDBCTemplate.update(2, 20);

System.out.println("----Listing Record with ID = 2 -----" );


Student student = studentJDBCTemplate.getStudent(2);
System.out.print("ID : " + student.getId() );
System.out.print(", Name : " + student.getName() );
System.out.println(", Age : " + student.getAge());
}
}

11 | P a g e

You might also like