SlideShare a Scribd company logo
Spring JDBC/DAO
By → Anuj Kumar Singh
What is Spring DAO (Data Access Object)
DAO is used to read and write data to and from database
respectively.The table below shows the responsibility of Spring and
User.
Note : The Spring Framework takes care of all the low-level details that
can make JDBC such a tedious API to develop with
Action Spring User
Define Connection Parameter Yes
Open the Connection Yes
Specify the SQL statement Yes
Declare parameters and provide parameter values Yes
Prepare and Execute the Statement Yes
Set up the loop to iterate through the result (if any) Yes
Do the work for each iteration Yes
Process any Exception Yes
Handle Transactions Yes
Close the Connection,Statement and ResultSet Yes
Steps for DAO
We have to follow three steps while configuring the Spring Context in
XML.
Step 1: Configure Data Source
1. Driver Based Data Source
2. JNDI Data Source
3. Pooled Data Source
Step 2: Configure JDBC Template
1. JDBC Template
2. NamedParameter JDBC Template
3. Simple JDBC Template
Step 3: Configure custom DAO Class
Step 1: Configure Data Source
The very first step you need to work on database is configuring the data
source in Spring’s context file. If you remember the basic steps of JDBC
Connection in Java, first we load the driver using Class.forName(), then
getting connection using DriverManager providing the URL such as
Connection con = DriverManager.getConnection(, ,) and then using
Statement or PreparedStatement. While configuring the DataSource in
Spring we may need to pass connection details (such as DriverName,
URL, Username, Password) to Spring framework. The benefit of
configuring data sources in this way is that they can be managed
completely external to the application, leaving the application to simply
ask for a data source when it’s ready to access the database.
1. Driver Based Data Source
It is the simplest data source that can be configured in Spring. This
should not be used in Production but it is good to use in Development
Environment for unit testing. There are Two data source classes.
• DriverManagerDataSource
• SingleConnectionDataSource
The basic difference is DriverManagerDataSource provides a new
connection each time, where as SingleConnectionDataSource provides
the same connection. Let’s see an example, to connect MySQL
database I am using com.mysql.jdbc.Driver class. And don’t need any
username or password. We use DriverManagerDataSource so the
configuration would be:
<bean id=”MyDataSource”
class=”org.springframework.jdbc.datasource.DriverManagerDataSource”>
<property name=”driverClassName” value=”com.mysql.jdbc.Driver”/>
<property name=”url” value=”jdbc:mysql://localhost/test”/ >
<property name=”username” value=””/>
<property name=”password” value=””/>
</bean>
How it is if we take the connection details (Driver class name, url,
username, password etc. ) from a property file rather than defining in
Spring Context XML file itself?
Yes, it is a good idea to take the database connection details from a
property file. So let’s create a property file. We will name the file as:
jdbc.properties
You need this extra entry to include the properties from jdbc.properties file.
Properties define in jdbc.properties file
2. JNDI (Java Naming and Directory Interface) DATA SOURCE
Application server are often pooled for greater performance. The
application servers such as WebSphere, WebLogic, Jboss allow to
configure connection pools. And these connection pools can be
retrieved through a JNDI. The benefit of configuring data sources in this
way is that they can be managed completely external to the application,
leaving the application to simply ask for a data source when it’s ready to
access the database.
In driver based data source, we saw any of the 2 classes
DriverManagerDataSource and SingleConnectionDataSource can be
used to establish the connection. Similarly for JNDI data source, we use
JndiObjectFactoryBean.
I have created a connection pool my application server. The JNDI name
is “mysqldatasource”. There is a servlet deployed in the same Server
which gets the DAO object from the Spring Container. Spring provided
the dataSource to the DAO after getting connection from the
connection-pool mysqldatasource.
3. Pooled Data Source
If you’re unable to retrieve a data source from JNDI, the next best thing
is to configure a pooled data source directly in Spring. Spring doesn’t
provide a pooled data source, there’s a suitable one available in the
Jakarta Commons Database Connection Pools (DBCP) project. To add
DBCP to your application, you need to download the JAR file and place
it into your build path along with spring library files.
The class you do use for Pooled Data Source is :
org.apache.commons.dbcp.BasicDataSource
Two new properties in Pooled Data Source
Step 2: Configure JDBC Template
After configuring the DataSource, the next step is configuring the
JDBCTemplate. The JdbcTemplate class is the central class in the
JDBC core package. It simplifies the use of JDBC since it handles the
creation and release of resources. This helps to avoid common errors
such as forgetting to always close the connection. It executes the core
JDBC workflow like statement creation and execution, leaving
application code to provide SQL and extract results. This class executes
SQL queries, update statements or stored procedure calls, imitating
iteration over ResultSets and 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.
Option 1: The JdbcTemplate can be used within a DAO implementation
via direct instantiation with a DataSource reference
OR
Option 2: be configured in a Spring IOC container and given to DAOs as
a bean reference.
Option 1: Explanation
The JdbcTemplate within a DAO implementation via direct instantiation
with a DataSource reference.
Option 2: Explanation
Configured in Spring IOC container and given JdbcTemplate to DAOs
as a bean reference.
Spring jdbc dao
Step 3: Writing DAO Layer
We already discussed that the JdbcTemplate can be used within a DAO
implementation via direct instantiation with a DataSource reference OR
be configured in a Spring IOC container and given to DAOs as a bean
reference. Now we will see how they can be implemented in the DAO
class.
Option 1: The JdbcTemplate within a DAO implementation via direct
instantiation with a DataSource reference.
We are injecting
DataSource but not
JDBCTemplate
In DAO Class
Created JDBCTemplate
instance and assign to
localobject
Using
JDBCTemplate
Option 2:
Configured in Spring IOC container and given JdbcTemplate to DAOs
as a bean reference.
Explanation :
In all our examples, we adopted this option only…
In DAO Class
Bean id must be
JDBCTemplate
JDBCTemplate not
DataSource
Spring jdbc dao

More Related Content

PPTX
Introduction à spring boot
PDF
Spring Boot
PPTX
DiI/DIコンテナを一から学んでみた
PPTX
Spring jdbc
PPTX
Spring boot - an introduction
PPTX
Spring boot Introduction
PDF
소프트웨어 아키텍처
PPTX
Spring mvc
Introduction à spring boot
Spring Boot
DiI/DIコンテナを一から学んでみた
Spring jdbc
Spring boot - an introduction
Spring boot Introduction
소프트웨어 아키텍처
Spring mvc

What's hot (20)

PDF
Spring core module
PDF
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
PPT
Introduction to Eclipse IDE
PDF
Java 8 features
PPTX
Introduction to spring boot
PPT
Presentation Spring, Spring MVC
PPTX
Introduction to Spring Framework
PDF
Redmineを使ってみよう
PDF
Spring Framework - Core
PDF
Google Web Toolkit
PPT
Spring Core
PDF
Introduction to Spring Framework
PPTX
Spring framework IOC and Dependency Injection
PPTX
Design pattern-presentation
PPTX
Hibernate jpa
PDF
Introduction to Java Programming Language
PPT
Strategy Design Pattern
PDF
React js
PPTX
Introduction to Maven
Spring core module
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
Introduction to Eclipse IDE
Java 8 features
Introduction to spring boot
Presentation Spring, Spring MVC
Introduction to Spring Framework
Redmineを使ってみよう
Spring Framework - Core
Google Web Toolkit
Spring Core
Introduction to Spring Framework
Spring framework IOC and Dependency Injection
Design pattern-presentation
Hibernate jpa
Introduction to Java Programming Language
Strategy Design Pattern
React js
Introduction to Maven
Ad

Similar to Spring jdbc dao (20)

PPTX
Spring framework DAO
PPTX
Spring database - part2
PDF
Spring db-access mod03
PPTX
Spring framework part 2
PPTX
Enterprise Spring
PDF
Spring Data JPA
PDF
springdatajpa-up.pdf
PPTX
Spring data jpa
PDF
Java e i database: da JDBC a JPA
PPTX
DBMS Architecture having normalisation he
PDF
JDBC, What Is It Good For?
DOC
Java database connectivity notes for undergraduate
PPTX
3 jdbc api
ODP
Polyglot persistence with Spring Data
PPTX
Configuring jpa in a Spring application
PDF
High performance database applications with pure query and ibm data studio.ba...
PPT
Chapter 2 Architecture and Classification of DBMS.ppt
PDF
Java Web Programming [3/9] : Servlet Advanced
PDF
Java Web Programming Using Cloud Platform: Module 3
PDF
Chapter (Two) The best lecture PowerPoint
Spring framework DAO
Spring database - part2
Spring db-access mod03
Spring framework part 2
Enterprise Spring
Spring Data JPA
springdatajpa-up.pdf
Spring data jpa
Java e i database: da JDBC a JPA
DBMS Architecture having normalisation he
JDBC, What Is It Good For?
Java database connectivity notes for undergraduate
3 jdbc api
Polyglot persistence with Spring Data
Configuring jpa in a Spring application
High performance database applications with pure query and ibm data studio.ba...
Chapter 2 Architecture and Classification of DBMS.ppt
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming Using Cloud Platform: Module 3
Chapter (Two) The best lecture PowerPoint
Ad

More from Anuj Singh Rajput (20)

PPTX
Web technology
PPTX
Java script
PPTX
Html (hypertext markup language)
PPTX
PPTX
Jsp session 13
PPTX
Jsp session 12
PPTX
Jsp session 11
PPTX
Jsp session 10
PPTX
Jsp session 9
PPTX
Jsp session 8
PPTX
Jsp session 7
PPTX
Jsp session 6
PPTX
Jsp session 5
PPTX
Jsp session 4
PPTX
Jsp session 3
PPTX
Jsp session 2
PPTX
Jsp session 1
PPTX
Servlet session 14
PPTX
Servlet session 13
Web technology
Java script
Html (hypertext markup language)
Jsp session 13
Jsp session 12
Jsp session 11
Jsp session 10
Jsp session 9
Jsp session 8
Jsp session 7
Jsp session 6
Jsp session 5
Jsp session 4
Jsp session 3
Jsp session 2
Jsp session 1
Servlet session 14
Servlet session 13

Recently uploaded (20)

PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
Updated Idioms and Phrasal Verbs in English subject
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
Trump Administration's workforce development strategy
PDF
Yogi Goddess Pres Conference Studio Updates
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
Classroom Observation Tools for Teachers
PPTX
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
RMMM.pdf make it easy to upload and study
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
PPTX
Cell Types and Its function , kingdom of life
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
01-Introduction-to-Information-Management.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Computing-Curriculum for Schools in Ghana
Final Presentation General Medicine 03-08-2024.pptx
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Updated Idioms and Phrasal Verbs in English subject
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Trump Administration's workforce development strategy
Yogi Goddess Pres Conference Studio Updates
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Classroom Observation Tools for Teachers
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
Final Presentation General Medicine 03-08-2024.pptx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
RMMM.pdf make it easy to upload and study
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
Cell Types and Its function , kingdom of life
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Weekly quiz Compilation Jan -July 25.pdf
01-Introduction-to-Information-Management.pdf

Spring jdbc dao

  • 1. Spring JDBC/DAO By → Anuj Kumar Singh
  • 2. What is Spring DAO (Data Access Object) DAO is used to read and write data to and from database respectively.The table below shows the responsibility of Spring and User. Note : The Spring Framework takes care of all the low-level details that can make JDBC such a tedious API to develop with
  • 3. Action Spring User Define Connection Parameter Yes Open the Connection Yes Specify the SQL statement Yes Declare parameters and provide parameter values Yes Prepare and Execute the Statement Yes Set up the loop to iterate through the result (if any) Yes Do the work for each iteration Yes Process any Exception Yes Handle Transactions Yes Close the Connection,Statement and ResultSet Yes
  • 4. Steps for DAO We have to follow three steps while configuring the Spring Context in XML. Step 1: Configure Data Source 1. Driver Based Data Source 2. JNDI Data Source 3. Pooled Data Source Step 2: Configure JDBC Template 1. JDBC Template 2. NamedParameter JDBC Template 3. Simple JDBC Template
  • 5. Step 3: Configure custom DAO Class Step 1: Configure Data Source The very first step you need to work on database is configuring the data source in Spring’s context file. If you remember the basic steps of JDBC Connection in Java, first we load the driver using Class.forName(), then getting connection using DriverManager providing the URL such as Connection con = DriverManager.getConnection(, ,) and then using Statement or PreparedStatement. While configuring the DataSource in Spring we may need to pass connection details (such as DriverName, URL, Username, Password) to Spring framework. The benefit of configuring data sources in this way is that they can be managed completely external to the application, leaving the application to simply ask for a data source when it’s ready to access the database.
  • 6. 1. Driver Based Data Source It is the simplest data source that can be configured in Spring. This should not be used in Production but it is good to use in Development Environment for unit testing. There are Two data source classes. • DriverManagerDataSource • SingleConnectionDataSource The basic difference is DriverManagerDataSource provides a new connection each time, where as SingleConnectionDataSource provides the same connection. Let’s see an example, to connect MySQL database I am using com.mysql.jdbc.Driver class. And don’t need any username or password. We use DriverManagerDataSource so the configuration would be:
  • 7. <bean id=”MyDataSource” class=”org.springframework.jdbc.datasource.DriverManagerDataSource”> <property name=”driverClassName” value=”com.mysql.jdbc.Driver”/> <property name=”url” value=”jdbc:mysql://localhost/test”/ > <property name=”username” value=””/> <property name=”password” value=””/> </bean>
  • 8. How it is if we take the connection details (Driver class name, url, username, password etc. ) from a property file rather than defining in Spring Context XML file itself? Yes, it is a good idea to take the database connection details from a property file. So let’s create a property file. We will name the file as: jdbc.properties
  • 9. You need this extra entry to include the properties from jdbc.properties file. Properties define in jdbc.properties file
  • 10. 2. JNDI (Java Naming and Directory Interface) DATA SOURCE Application server are often pooled for greater performance. The application servers such as WebSphere, WebLogic, Jboss allow to configure connection pools. And these connection pools can be retrieved through a JNDI. The benefit of configuring data sources in this way is that they can be managed completely external to the application, leaving the application to simply ask for a data source when it’s ready to access the database. In driver based data source, we saw any of the 2 classes DriverManagerDataSource and SingleConnectionDataSource can be used to establish the connection. Similarly for JNDI data source, we use JndiObjectFactoryBean.
  • 11. I have created a connection pool my application server. The JNDI name is “mysqldatasource”. There is a servlet deployed in the same Server which gets the DAO object from the Spring Container. Spring provided the dataSource to the DAO after getting connection from the connection-pool mysqldatasource.
  • 12. 3. Pooled Data Source If you’re unable to retrieve a data source from JNDI, the next best thing is to configure a pooled data source directly in Spring. Spring doesn’t provide a pooled data source, there’s a suitable one available in the Jakarta Commons Database Connection Pools (DBCP) project. To add DBCP to your application, you need to download the JAR file and place it into your build path along with spring library files. The class you do use for Pooled Data Source is : org.apache.commons.dbcp.BasicDataSource
  • 13. Two new properties in Pooled Data Source
  • 14. Step 2: Configure JDBC Template After configuring the DataSource, the next step is configuring the JDBCTemplate. The JdbcTemplate class is the central class in the JDBC core package. It simplifies the use of JDBC since it handles the creation and release of resources. This helps to avoid common errors such as forgetting to always close the connection. It executes the core JDBC workflow like statement creation and execution, leaving application code to provide SQL and extract results. This class executes SQL queries, update statements or stored procedure calls, imitating iteration over ResultSets and 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.
  • 15. Option 1: The JdbcTemplate can be used within a DAO implementation via direct instantiation with a DataSource reference OR Option 2: be configured in a Spring IOC container and given to DAOs as a bean reference. Option 1: Explanation The JdbcTemplate within a DAO implementation via direct instantiation with a DataSource reference.
  • 16. Option 2: Explanation Configured in Spring IOC container and given JdbcTemplate to DAOs as a bean reference.
  • 18. Step 3: Writing DAO Layer We already discussed that the JdbcTemplate can be used within a DAO implementation via direct instantiation with a DataSource reference OR be configured in a Spring IOC container and given to DAOs as a bean reference. Now we will see how they can be implemented in the DAO class. Option 1: The JdbcTemplate within a DAO implementation via direct instantiation with a DataSource reference.
  • 19. We are injecting DataSource but not JDBCTemplate In DAO Class Created JDBCTemplate instance and assign to localobject Using JDBCTemplate
  • 20. Option 2: Configured in Spring IOC container and given JdbcTemplate to DAOs as a bean reference. Explanation : In all our examples, we adopted this option only…
  • 21. In DAO Class Bean id must be JDBCTemplate JDBCTemplate not DataSource