SlideShare a Scribd company logo
1 of 22
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.
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

What's hot

Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action Alex Movila
 
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...Edureka!
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Edureka!
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introductionJonathan Holloway
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
 
Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)Luzan Baral
 
What Is Spring Framework In Java | Spring Framework Tutorial For Beginners Wi...
What Is Spring Framework In Java | Spring Framework Tutorial For Beginners Wi...What Is Spring Framework In Java | Spring Framework Tutorial For Beginners Wi...
What Is Spring Framework In Java | Spring Framework Tutorial For Beginners Wi...Edureka!
 
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...Pallepati Vasavi
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring FrameworkASG
 

What's hot (20)

Jsf presentation
Jsf presentationJsf presentation
Jsf presentation
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
What Is Spring Framework In Java | Spring Framework Tutorial For Beginners Wi...
What Is Spring Framework In Java | Spring Framework Tutorial For Beginners Wi...What Is Spring Framework In Java | Spring Framework Tutorial For Beginners Wi...
What Is Spring Framework In Java | Spring Framework Tutorial For Beginners Wi...
 
Jdbc complete
Jdbc completeJdbc complete
Jdbc complete
 
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Jdbc_ravi_2016
Jdbc_ravi_2016Jdbc_ravi_2016
Jdbc_ravi_2016
 

Similar to Spring jdbc dao

Similar to Spring jdbc dao (20)

Spring database - part2
Spring database -  part2Spring database -  part2
Spring database - part2
 
Spring framework DAO
Spring framework  DAOSpring framework  DAO
Spring framework DAO
 
Enterprise Spring
Enterprise SpringEnterprise Spring
Enterprise Spring
 
JDBC
JDBCJDBC
JDBC
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
 
Final Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.pptFinal Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.ppt
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Java Data Base Connectivity concepts.pptx
Java Data Base Connectivity concepts.pptxJava Data Base Connectivity concepts.pptx
Java Data Base Connectivity concepts.pptx
 
Core jdbc basics
Core jdbc basicsCore jdbc basics
Core jdbc basics
 
JDBC-Introduction
JDBC-IntroductionJDBC-Introduction
JDBC-Introduction
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Assignment#10
Assignment#10Assignment#10
Assignment#10
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
3 jdbc
3 jdbc3 jdbc
3 jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)
 
Jdbc
JdbcJdbc
Jdbc
 
Overview Of JDBC
Overview Of JDBCOverview Of JDBC
Overview Of JDBC
 
03-JDBC.pptx
03-JDBC.pptx03-JDBC.pptx
03-JDBC.pptx
 

More from Anuj Singh Rajput (20)

Web technology
Web technologyWeb technology
Web technology
 
Java script
Java scriptJava script
Java script
 
Html (hypertext markup language)
Html (hypertext markup language)Html (hypertext markup language)
Html (hypertext markup language)
 
Css
CssCss
Css
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
Jsp session 13
Jsp   session 13Jsp   session 13
Jsp session 13
 
Jsp session 12
Jsp   session 12Jsp   session 12
Jsp session 12
 
Jsp session 11
Jsp   session 11Jsp   session 11
Jsp session 11
 
Jsp session 10
Jsp   session 10Jsp   session 10
Jsp session 10
 
Jsp session 9
Jsp   session 9Jsp   session 9
Jsp session 9
 
Jsp session 8
Jsp   session 8Jsp   session 8
Jsp session 8
 
Jsp session 7
Jsp   session 7Jsp   session 7
Jsp session 7
 
Jsp session 6
Jsp   session 6Jsp   session 6
Jsp session 6
 
Jsp session 5
Jsp   session 5Jsp   session 5
Jsp session 5
 
Jsp session 4
Jsp   session 4Jsp   session 4
Jsp session 4
 
Jsp session 3
Jsp   session 3Jsp   session 3
Jsp session 3
 
Jsp session 2
Jsp   session 2Jsp   session 2
Jsp session 2
 
Jsp session 1
Jsp   session 1Jsp   session 1
Jsp session 1
 
Servlet session 14
Servlet   session 14Servlet   session 14
Servlet session 14
 
Servlet session 13
Servlet   session 13Servlet   session 13
Servlet session 13
 

Recently uploaded

Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 

Recently uploaded (20)

Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 

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.
  • 17.
  • 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