SlideShare a Scribd company logo
Database Access Using the
Spring Framework
What this presentation will be

   Brief overview of wiring applications using
    Spring
   Using Spring’s JDBC framework
   Spring’s transaction support
What this presentation will not cover

   In-depth coverage of Spring
   Creating web applications using Spring
Overview of wiring with Spring

   Discuss…
Concerns when accessing database

   Managing transactions
   Managing resources
       Connection pooling
       Cleaning up resources
Some typical JDBC code



      Code Example
The problem with traditional JDBC code

   It’s redundant
   It repeats itself quite a bit
   The exact same code appears in lots of
    places
   You find yourself doing the same things over
    and over again
   It’s redundant
The problem with redundant code

   Violates the DRY principle
   Maintenance nightmare since JDBC code is
    inherently messy
   JDBC code is critical, so it is important to get
    it right, once
Spring’s solution – The Template Pattern

   Template Pattern – “Define the skeleton of an
    algorithm in an operation, deferring some
    steps to subclasses. Template Method lets
    subclasses redefine certain steps of an
    algorithm without changing the algorithm's
    structure.”
   Uses “callbacks” for implementation specific
    tasks
So what do this mean in a JDBC context?

       DAO Template             Your code

   1. Prepare Resources   3. Execute Statement
   2. Start Transaction



   5. Commit/Rollback     4. Execute Statement
   6. Clean up resource
   7. Handle exceptions
But before we get too far ahead…
…let’s see how we
   Obtain/create a DataSource
   Wire a DataSource to our XxxDao classes
Working with DataSources
Getting a DataSource from JNDI
<bean id=“dataSource”
      class=“org.springframework.jndi.JndiObjectFactoryBean”>
  <property name=“jndiName”
            value=“java:comp/env/jdbc/MyDataSourceName”/>
</bean>
Working with DataSources

Creating a connection pool
<bean id=“dataSource” class=“org.apache.commons.dbcp.BasicDataSource”>
  <property   name="url“ value=“jdbc:mysql://localhost/demo”/>>
  <property   name="driverClassName“ value=“com.mysql.jdbc.Driver”/>
  <property   name="username” value=“test”/>
  <property   name=“password” value=“password”/>
</bean>
Working with DataSources



      Code Example
Overview of Spring JDBC features

   As mentioned, provides framework so that
    Spring manages:
       Resources
       Transactions
       Exceptions
   Consistent exception hierarchy
       Subclass RuntimeException
       Specific and meaningful (no vendor error codes!)
       Extensable
Some Spring JDBC callback interfaces

   PreparedStatementCreator
       Has one method –
        createPreparedStatement(Connection)
       Responsible for creating a PreparedStatement
       Does not need to handle SQLExceptions
Some Spring JDBC callback interfaces

   SQLProvider
       Has one method – getSql()
       Typically implemented by
        PreparedStatementCreator implementers
       Useful for debugging
Some Spring JDBC callback interfaces

   RowCallbackHandler
       Has one method – processRow(ResultSet)
       Called for each row in ResultSet
       Typically stateful
Some Spring JDBC callback interfaces

   RowMapper
       Has one method – mapRow(ResultSet rs,
        int rowNum)
       Maps a single row to an Object
Using JdbcTemplate

   Central class for Spring JDBC framework
   Uses callbacks “under the covers”
   All you will need for most JDBC operations
Using JdbcTemplate



      Code Example
Spring Incrementers

   Used to increment primary key value for
    newly persisted object
   Implements
    DataFieldMaxValueIncrementer
   Supports
       Oracle sequences
       DB2 sequences
       PostgreSQL sequences
       MySQL for non-auto-increment columns
Using JdbcTemplate



      Code Example
Hibernate intro

   Open source ORM tool
   Very mature (version 3.2 on horizon)
   Feature-complete
       Caching
       Eager-fetching
       Lazy-loading
       Proxying
Using Hibernate

   Configure classes to be mapped through
       Manually created configuration files
       XDoclet generated configuration files
       Annotations (JPA and Hibernate)
   Configure global properties through
    hibernate.properties file
   Hibernate class analogies
       DataSource : SessionFactory
       Connection : Session
Using Spring with Hibernate

   Use Spring to configure Hibernate
     Configure Hibernate mappings
     Configure Hibernate properties

     Wire dependant object to SessionFactory

   Use HibernateTemplate as abstraction to
    Hibernate API
       Manages obtaining Session from
        SessionFactory
       Handles/converts exceptions
       Manages transactions
Using JdbcTemplate



      Code Example
Spring Transaction Management

   Supports programmatic (yuck!) and declarative
    (yeah!) transactions
   Declarative transaction management achieved via
    Spring’s AOP
   Declarative transactions can be defined in Spring
    configuration file or in annotations
   Supports many transaction properties
       Propagation
       Isolation level
       Rollback conditions
Spring Proxy Overview



                    depends on
  SomeClient                        DaoInterface




         is wired                   delegates
                        ProxyBean                  DaoImpl
Using JdbcTemplate



      Code Example
Coming in Spring 2.0

   Support for AspectJ pointcut language
   JPA support?
   SimpleJdbcTemplate
       Support generics
       Support variable argument methods
Ad

More Related Content

What's hot (19)

Hibernate
HibernateHibernate
Hibernate
Prashant Kalkar
 
Jdbc connectivity in java
Jdbc connectivity in javaJdbc connectivity in java
Jdbc connectivity in java
Muthukumaran Subramanian
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
Fad Zulkifli
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
backdoor
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
Manav Prasad
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
hameedkhan2017
 
Hibernate
HibernateHibernate
Hibernate
Ajay K
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
John Slick
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
Aneega
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
Mumbai Academisc
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
Dharani Kumar Madduri
 
Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)
Igor Anishchenko
 
Hibernate in Nutshell
Hibernate in NutshellHibernate in Nutshell
Hibernate in Nutshell
Onkar Deshpande
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
Rahul Jain
 
Spring & hibernate
Spring & hibernateSpring & hibernate
Spring & hibernate
Santosh Kumar Kar
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
Raveendra R
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
kamal kotecha
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
Fad Zulkifli
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
backdoor
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
Manav Prasad
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
Hibernate
HibernateHibernate
Hibernate
Ajay K
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
John Slick
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
Aneega
 
Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)
Igor Anishchenko
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
Rahul Jain
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
Raveendra R
 

Similar to Spring db-access mod03 (20)

Jdjdbcbc Jdjdbcbc JdjdbcJdjdbcbc Jdjdbcbc Jdjdbcbcbc JdJdbcbc
Jdjdbcbc Jdjdbcbc JdjdbcJdjdbcbc Jdjdbcbc Jdjdbcbcbc JdJdbcbcJdjdbcbc Jdjdbcbc JdjdbcJdjdbcbc Jdjdbcbc Jdjdbcbcbc JdJdbcbc
Jdjdbcbc Jdjdbcbc JdjdbcJdjdbcbc Jdjdbcbc Jdjdbcbcbc JdJdbcbc
rohanbawadkar
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
Rakesh Kumar Ray
 
Complete java syllabus 7448062045 Yesdo Sddd
Complete java syllabus 7448062045 Yesdo SdddComplete java syllabus 7448062045 Yesdo Sddd
Complete java syllabus 7448062045 Yesdo Sddd
Yesdo Softindia Pvt Ltd
 
Jdbc
JdbcJdbc
Jdbc
DeepikaT13
 
Rollin onj Rubyv3
Rollin onj Rubyv3Rollin onj Rubyv3
Rollin onj Rubyv3
Oracle
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
Haroon Idrees
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
Harshit Choudhary
 
JDBC
JDBCJDBC
JDBC
Manjunatha RK
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.ppt
kingkolju
 
Jdbc
JdbcJdbc
Jdbc
Yamuna Devi
 
EJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkEJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLink
Bill Lyons
 
High Performance Jdbc
High Performance JdbcHigh Performance Jdbc
High Performance Jdbc
Sam Pattsin
 
Jdbc
Jdbc   Jdbc
Jdbc
Ishucs
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
DrMeenakshiS
 
Jdbc Lecture5
Jdbc Lecture5Jdbc Lecture5
Jdbc Lecture5
phanleson
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5
Smita B Kumar
 
Enterprise Spring
Enterprise SpringEnterprise Spring
Enterprise Spring
Emprovise
 
Java Database Connectivity by shreyash simu dbce.pptx
Java Database Connectivity by shreyash simu dbce.pptxJava Database Connectivity by shreyash simu dbce.pptx
Java Database Connectivity by shreyash simu dbce.pptx
ash909077
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
Maher Abdo
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
Tanmoy Barman
 
Jdjdbcbc Jdjdbcbc JdjdbcJdjdbcbc Jdjdbcbc Jdjdbcbcbc JdJdbcbc
Jdjdbcbc Jdjdbcbc JdjdbcJdjdbcbc Jdjdbcbc Jdjdbcbcbc JdJdbcbcJdjdbcbc Jdjdbcbc JdjdbcJdjdbcbc Jdjdbcbc Jdjdbcbcbc JdJdbcbc
Jdjdbcbc Jdjdbcbc JdjdbcJdjdbcbc Jdjdbcbc Jdjdbcbcbc JdJdbcbc
rohanbawadkar
 
Complete java syllabus 7448062045 Yesdo Sddd
Complete java syllabus 7448062045 Yesdo SdddComplete java syllabus 7448062045 Yesdo Sddd
Complete java syllabus 7448062045 Yesdo Sddd
Yesdo Softindia Pvt Ltd
 
Rollin onj Rubyv3
Rollin onj Rubyv3Rollin onj Rubyv3
Rollin onj Rubyv3
Oracle
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
Haroon Idrees
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.ppt
kingkolju
 
EJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkEJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLink
Bill Lyons
 
High Performance Jdbc
High Performance JdbcHigh Performance Jdbc
High Performance Jdbc
Sam Pattsin
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
DrMeenakshiS
 
Jdbc Lecture5
Jdbc Lecture5Jdbc Lecture5
Jdbc Lecture5
phanleson
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5
Smita B Kumar
 
Enterprise Spring
Enterprise SpringEnterprise Spring
Enterprise Spring
Emprovise
 
Java Database Connectivity by shreyash simu dbce.pptx
Java Database Connectivity by shreyash simu dbce.pptxJava Database Connectivity by shreyash simu dbce.pptx
Java Database Connectivity by shreyash simu dbce.pptx
ash909077
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
Maher Abdo
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
Tanmoy Barman
 
Ad

More from Guo Albert (20)

AWS IAM (Identity and Access Management) Policy Simulator
AWS IAM (Identity and Access Management) Policy SimulatorAWS IAM (Identity and Access Management) Policy Simulator
AWS IAM (Identity and Access Management) Policy Simulator
Guo Albert
 
TOEIC 準備心得
TOEIC 準備心得TOEIC 準備心得
TOEIC 準備心得
Guo Albert
 
DBM專案環境建置
DBM專案環境建置DBM專案環境建置
DBM專案環境建置
Guo Albert
 
JPA Optimistic Locking With @Version
JPA Optimistic Locking With @VersionJPA Optimistic Locking With @Version
JPA Optimistic Locking With @Version
Guo Albert
 
OCEJPA Study Notes
OCEJPA Study NotesOCEJPA Study Notes
OCEJPA Study Notes
Guo Albert
 
OCEJPA(1Z0-898) Preparation Tips
OCEJPA(1Z0-898) Preparation TipsOCEJPA(1Z0-898) Preparation Tips
OCEJPA(1Z0-898) Preparation Tips
Guo Albert
 
JPA lifecycle events practice
JPA lifecycle events practiceJPA lifecycle events practice
JPA lifecycle events practice
Guo Albert
 
XDate - a modern java-script date library
XDate -  a modern java-script date libraryXDate -  a modern java-script date library
XDate - a modern java-script date library
Guo Albert
 
How to avoid check style errors
How to avoid check style errorsHow to avoid check style errors
How to avoid check style errors
Guo Albert
 
NIG系統報表開發指南
NIG系統報表開發指南NIG系統報表開發指南
NIG系統報表開發指南
Guo Albert
 
Ease Your Effort of Putting Data into History Table
Ease Your Effort of Putting Data into History TableEase Your Effort of Putting Data into History Table
Ease Your Effort of Putting Data into History Table
Guo Albert
 
NIG 系統開發指引
NIG 系統開發指引NIG 系統開發指引
NIG 系統開發指引
Guo Albert
 
NIG系統開發文件閱讀步驟
NIG系統開發文件閱讀步驟NIG系統開發文件閱讀步驟
NIG系統開發文件閱讀步驟
Guo Albert
 
Form Bean Creation Process for NIG System
Form Bean Creation Process for NIG SystemForm Bean Creation Process for NIG System
Form Bean Creation Process for NIG System
Guo Albert
 
A Short Intorduction to JasperReports
A Short Intorduction to JasperReportsA Short Intorduction to JasperReports
A Short Intorduction to JasperReports
Guo Albert
 
Apply Template Method Pattern in Report Implementation
Apply Template Method Pattern in Report ImplementationApply Template Method Pattern in Report Implementation
Apply Template Method Pattern in Report Implementation
Guo Albert
 
Utilize Commons BeansUtils to do copy object
Utilize Commons BeansUtils to do copy objectUtilize Commons BeansUtils to do copy object
Utilize Commons BeansUtils to do copy object
Guo Albert
 
Apply my eclipse to do entity class generation
Apply my eclipse to do entity class generationApply my eclipse to do entity class generation
Apply my eclipse to do entity class generation
Guo Albert
 
Nig project setup quickly tutorial
Nig project setup quickly tutorialNig project setup quickly tutorial
Nig project setup quickly tutorial
Guo Albert
 
Spring JDBCTemplate
Spring JDBCTemplateSpring JDBCTemplate
Spring JDBCTemplate
Guo Albert
 
AWS IAM (Identity and Access Management) Policy Simulator
AWS IAM (Identity and Access Management) Policy SimulatorAWS IAM (Identity and Access Management) Policy Simulator
AWS IAM (Identity and Access Management) Policy Simulator
Guo Albert
 
TOEIC 準備心得
TOEIC 準備心得TOEIC 準備心得
TOEIC 準備心得
Guo Albert
 
DBM專案環境建置
DBM專案環境建置DBM專案環境建置
DBM專案環境建置
Guo Albert
 
JPA Optimistic Locking With @Version
JPA Optimistic Locking With @VersionJPA Optimistic Locking With @Version
JPA Optimistic Locking With @Version
Guo Albert
 
OCEJPA Study Notes
OCEJPA Study NotesOCEJPA Study Notes
OCEJPA Study Notes
Guo Albert
 
OCEJPA(1Z0-898) Preparation Tips
OCEJPA(1Z0-898) Preparation TipsOCEJPA(1Z0-898) Preparation Tips
OCEJPA(1Z0-898) Preparation Tips
Guo Albert
 
JPA lifecycle events practice
JPA lifecycle events practiceJPA lifecycle events practice
JPA lifecycle events practice
Guo Albert
 
XDate - a modern java-script date library
XDate -  a modern java-script date libraryXDate -  a modern java-script date library
XDate - a modern java-script date library
Guo Albert
 
How to avoid check style errors
How to avoid check style errorsHow to avoid check style errors
How to avoid check style errors
Guo Albert
 
NIG系統報表開發指南
NIG系統報表開發指南NIG系統報表開發指南
NIG系統報表開發指南
Guo Albert
 
Ease Your Effort of Putting Data into History Table
Ease Your Effort of Putting Data into History TableEase Your Effort of Putting Data into History Table
Ease Your Effort of Putting Data into History Table
Guo Albert
 
NIG 系統開發指引
NIG 系統開發指引NIG 系統開發指引
NIG 系統開發指引
Guo Albert
 
NIG系統開發文件閱讀步驟
NIG系統開發文件閱讀步驟NIG系統開發文件閱讀步驟
NIG系統開發文件閱讀步驟
Guo Albert
 
Form Bean Creation Process for NIG System
Form Bean Creation Process for NIG SystemForm Bean Creation Process for NIG System
Form Bean Creation Process for NIG System
Guo Albert
 
A Short Intorduction to JasperReports
A Short Intorduction to JasperReportsA Short Intorduction to JasperReports
A Short Intorduction to JasperReports
Guo Albert
 
Apply Template Method Pattern in Report Implementation
Apply Template Method Pattern in Report ImplementationApply Template Method Pattern in Report Implementation
Apply Template Method Pattern in Report Implementation
Guo Albert
 
Utilize Commons BeansUtils to do copy object
Utilize Commons BeansUtils to do copy objectUtilize Commons BeansUtils to do copy object
Utilize Commons BeansUtils to do copy object
Guo Albert
 
Apply my eclipse to do entity class generation
Apply my eclipse to do entity class generationApply my eclipse to do entity class generation
Apply my eclipse to do entity class generation
Guo Albert
 
Nig project setup quickly tutorial
Nig project setup quickly tutorialNig project setup quickly tutorial
Nig project setup quickly tutorial
Guo Albert
 
Spring JDBCTemplate
Spring JDBCTemplateSpring JDBCTemplate
Spring JDBCTemplate
Guo Albert
 
Ad

Recently uploaded (20)

Open Access: Revamping Library Learning Resources.
Open Access: Revamping Library Learning Resources.Open Access: Revamping Library Learning Resources.
Open Access: Revamping Library Learning Resources.
Rishi Bankim Chandra Evening College, Naihati, North 24 Parganas, West Bengal, India
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
Fundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic CommunicationsFundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic Communications
Jordan Williams
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Envenomation---Clinical Toxicology. pptx
Envenomation---Clinical Toxicology. pptxEnvenomation---Clinical Toxicology. pptx
Envenomation---Clinical Toxicology. pptx
rekhapositivity
 
High Performance Liquid Chromatography .pptx
High Performance Liquid Chromatography .pptxHigh Performance Liquid Chromatography .pptx
High Performance Liquid Chromatography .pptx
Ayush Srivastava
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Studying Drama: Definition, types and elements
Studying Drama: Definition, types and elementsStudying Drama: Definition, types and elements
Studying Drama: Definition, types and elements
AbdelFattahAdel2
 
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd yearVitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
ARUN KUMAR
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Unit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its typesUnit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its types
bharath321164
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Fundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic CommunicationsFundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic Communications
Jordan Williams
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Envenomation---Clinical Toxicology. pptx
Envenomation---Clinical Toxicology. pptxEnvenomation---Clinical Toxicology. pptx
Envenomation---Clinical Toxicology. pptx
rekhapositivity
 
High Performance Liquid Chromatography .pptx
High Performance Liquid Chromatography .pptxHigh Performance Liquid Chromatography .pptx
High Performance Liquid Chromatography .pptx
Ayush Srivastava
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Studying Drama: Definition, types and elements
Studying Drama: Definition, types and elementsStudying Drama: Definition, types and elements
Studying Drama: Definition, types and elements
AbdelFattahAdel2
 
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd yearVitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
ARUN KUMAR
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Unit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its typesUnit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its types
bharath321164
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 

Spring db-access mod03

  • 1. Database Access Using the Spring Framework
  • 2. What this presentation will be  Brief overview of wiring applications using Spring  Using Spring’s JDBC framework  Spring’s transaction support
  • 3. What this presentation will not cover  In-depth coverage of Spring  Creating web applications using Spring
  • 4. Overview of wiring with Spring  Discuss…
  • 5. Concerns when accessing database  Managing transactions  Managing resources  Connection pooling  Cleaning up resources
  • 6. Some typical JDBC code Code Example
  • 7. The problem with traditional JDBC code  It’s redundant  It repeats itself quite a bit  The exact same code appears in lots of places  You find yourself doing the same things over and over again  It’s redundant
  • 8. The problem with redundant code  Violates the DRY principle  Maintenance nightmare since JDBC code is inherently messy  JDBC code is critical, so it is important to get it right, once
  • 9. Spring’s solution – The Template Pattern  Template Pattern – “Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.”  Uses “callbacks” for implementation specific tasks
  • 10. So what do this mean in a JDBC context? DAO Template Your code 1. Prepare Resources 3. Execute Statement 2. Start Transaction 5. Commit/Rollback 4. Execute Statement 6. Clean up resource 7. Handle exceptions
  • 11. But before we get too far ahead… …let’s see how we  Obtain/create a DataSource  Wire a DataSource to our XxxDao classes
  • 12. Working with DataSources Getting a DataSource from JNDI <bean id=“dataSource” class=“org.springframework.jndi.JndiObjectFactoryBean”> <property name=“jndiName” value=“java:comp/env/jdbc/MyDataSourceName”/> </bean>
  • 13. Working with DataSources Creating a connection pool <bean id=“dataSource” class=“org.apache.commons.dbcp.BasicDataSource”> <property name="url“ value=“jdbc:mysql://localhost/demo”/>> <property name="driverClassName“ value=“com.mysql.jdbc.Driver”/> <property name="username” value=“test”/> <property name=“password” value=“password”/> </bean>
  • 14. Working with DataSources Code Example
  • 15. Overview of Spring JDBC features  As mentioned, provides framework so that Spring manages:  Resources  Transactions  Exceptions  Consistent exception hierarchy  Subclass RuntimeException  Specific and meaningful (no vendor error codes!)  Extensable
  • 16. Some Spring JDBC callback interfaces  PreparedStatementCreator  Has one method – createPreparedStatement(Connection)  Responsible for creating a PreparedStatement  Does not need to handle SQLExceptions
  • 17. Some Spring JDBC callback interfaces  SQLProvider  Has one method – getSql()  Typically implemented by PreparedStatementCreator implementers  Useful for debugging
  • 18. Some Spring JDBC callback interfaces  RowCallbackHandler  Has one method – processRow(ResultSet)  Called for each row in ResultSet  Typically stateful
  • 19. Some Spring JDBC callback interfaces  RowMapper  Has one method – mapRow(ResultSet rs, int rowNum)  Maps a single row to an Object
  • 20. Using JdbcTemplate  Central class for Spring JDBC framework  Uses callbacks “under the covers”  All you will need for most JDBC operations
  • 21. Using JdbcTemplate Code Example
  • 22. Spring Incrementers  Used to increment primary key value for newly persisted object  Implements DataFieldMaxValueIncrementer  Supports  Oracle sequences  DB2 sequences  PostgreSQL sequences  MySQL for non-auto-increment columns
  • 23. Using JdbcTemplate Code Example
  • 24. Hibernate intro  Open source ORM tool  Very mature (version 3.2 on horizon)  Feature-complete  Caching  Eager-fetching  Lazy-loading  Proxying
  • 25. Using Hibernate  Configure classes to be mapped through  Manually created configuration files  XDoclet generated configuration files  Annotations (JPA and Hibernate)  Configure global properties through hibernate.properties file  Hibernate class analogies  DataSource : SessionFactory  Connection : Session
  • 26. Using Spring with Hibernate  Use Spring to configure Hibernate  Configure Hibernate mappings  Configure Hibernate properties  Wire dependant object to SessionFactory  Use HibernateTemplate as abstraction to Hibernate API  Manages obtaining Session from SessionFactory  Handles/converts exceptions  Manages transactions
  • 27. Using JdbcTemplate Code Example
  • 28. Spring Transaction Management  Supports programmatic (yuck!) and declarative (yeah!) transactions  Declarative transaction management achieved via Spring’s AOP  Declarative transactions can be defined in Spring configuration file or in annotations  Supports many transaction properties  Propagation  Isolation level  Rollback conditions
  • 29. Spring Proxy Overview depends on SomeClient DaoInterface is wired delegates ProxyBean DaoImpl
  • 30. Using JdbcTemplate Code Example
  • 31. Coming in Spring 2.0  Support for AspectJ pointcut language  JPA support?  SimpleJdbcTemplate  Support generics  Support variable argument methods