Spring JDBC
Overview of Spring JDBC
• While working with 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,
• Preparing and executing the SQL statement,
• Processing exceptions,
• Handling transactions, and
• Finally closing the connection.
Overview of Spring JDBC
• What you have do is just
• define connection parameters
• driverClassName
• url
• Username
• password
• Specify the SQL statement to be executed and do the required work for each
iteration while fetching data from the database.
Spring JDBC Configuration
Data Source
(Interface)
driverClassNam Spring Bean Configuration : Dependency Injection
e
Data Source url
User
password
=> Update()
=> queryForObject ()
Þ query()
Þ ……
JdbcTemplate
DriverManagerDataSource
JDBC Template Class
• JDBC Template class
• executes SQL queries and updates statements , performs iteration over
ResultSets
• Extraction of 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.
• 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
Spring Configuration File to create
bean of the JdbcTemplate Class
JdbcTemplate
• JdbcTemplate is a class which will help us to query the
database
• update()is a method provided by JdbcTemplate, which is used to
update the java object into the database
• Used to execute Insert , update and delete sql statemsts
• It takes 2 parameters, sql_query and parameters
• For ex.
Student s = new Student(101,”Amit”, “Prayagraj”);
String query = “Insert into student(id, name,address) values(?,?,?)”
jdbcTemplate.update (query, s.getid(), s.getName(), s.getAddress());
JdbcTemplate(Cont..)
• Query for Single Row
• queryForObject() to query a single row record from database, and
convert the row into an object via row mapper.
• Ex.
String query = “select * from student where id=101”;
Student s = jdbcTemplate.queryForObject(query, StudentRowWrapper);
• Query for Multiple Rows
• jdbcTemplate.query() used to submit select query for multiple rows
• It takes two arguments select query and RowWrapper
Ex.
String query = “ Select * From Student”;
List <Student> students = jdbcTemplate.execute(query, new StudentRowWrapper);