DATA ACCESS WITH JDBC
HARSHIT CHOUDHARY
OUTLINE
 Spring Data Access
 DAO Support
 Introduction to Spring Framework JDBC
 Using JDBC Core Classes
 Controlling Database connections
HARSHIT CHOUDHARY
DAO SUPPORT IN SPRING
HARSHIT CHOUDHARY
INTRODUCTION
 The Data Access Object (DAO) is a pattern to access the data of the database
 DAO Support in Spring makes it easy to work with data access technologies in a consistent
way
 This allows to switch between different persistence technologies easily and without catching
technology specific exceptions
HARSHIT CHOUDHARY
CONSISTENT EXCEPTION HIERARCHY
 Spring provides a convenient translation from technology-specific exception to its own exception class
hierarchy.
 These exceptions wrap the original exception so there is never risk to loose any information
 DataAccessException is the root exception in Spring, which is a Runtime Exception and developers are
not forced to handle the exception
HARSHIT CHOUDHARY
SPRING EXCEPTION HIERARCHY
HARSHIT CHOUDHARY
ANNOTATION FOR CONFIGURING DAO CLASSES
 @Repository
 Provides exception translation
 Allows component scanning support
HARSHIT CHOUDHARY
DATA ACCESS WITH JDBC
HARSHIT CHOUDHARY
OVERVIEW
 Spring JDBC Framework allows developers to focus on core logic
 Spring handles all the low level details and repetitive tasks like opening and closing of connections,
exceptions, iteration of resultsets, transactions etc.
 The table in next slide shows what actions spring take care of and which actions are responsibility of
application developer
HARSHIT CHOUDHARY
SPRING JDBC – WHO DOES WHAT?
HARSHIT CHOUDHARY
Action Spring You
Define connection parameters. X
Open the connection. X
Specify the SQL statement. X
Declare parameters and provide
parameter values
X
Prepare and execute the statement. X
Set up the loop to iterate through
the results (if any).
X
Do the work for each iteration. X
Process any exception. X
Handle transactions. X
Close the connection, statement and
resultset.
X
SPRING DATA ACCESS APPROACHES
 JdbcTemplate –
 JdbcTemplate approach works for JDK 1.4 onwards and is widely used.
 It is used internally in other three approaches.
 handles the repetitive operations like opening and closing of connections and can execute select, insert, update statements, calls to stored procedures.
 This class is thread safe.
 NamedParameterJdbcTemplate –
 supports the use of named parameters in place of traditional place holders ( ? ) and works with JDK 1.4 onwards.
 SimpleJdbcTemplate-
 Uses both JdbcTemplate and NamedParameterJdbcTemplate approaches and provides additional support of Java 5 features etc.
 This approach requires JDK 5 onwards.
 Deprecated in Spring 4.x onwards
 SimpleJdbcInsert and SimpleJdbcCall –
 utilizes the database metadata and hence reduces the configuration overhead.
HARSHIT CHOUDHARY
PACKAGE HIERARCHY
 The framework consists of 4 packages
 Core
 Contains JDBCTemplate class and its various call back interfaces
Subpackages of Core
 Simple
 Contains the SimpleJdbcInsert and SimpleJdbcCall classes
 Namedparam
 Contains the NamedParameterJdbcTemplate class
 Datasource
 Utility class for easy DataSource access and various simple DataSource implementations
 Object
 Contains classes that represent RDBMS queries, updates and stored procedures as thread-safe reusable objects
 Support
 Provides SQLException translation functionality and some utility classes. Exceptions thrown during JDBC processing are translated to exceptions defined in
org.springframework.dao package
HARSHIT CHOUDHARY
JDBCTEMPLATE CLASS
 Central class in the JDBC core package
 Handles creation and release of resources, and statement creation and execution
 Executes SQL queries, update statements and stored procedure calls, perform iteration over ResultSet and
extraction of returned parameter values.
 Catches SQL Exceptions and translate them to related subclass of DataAccessException
 JdbcTemplate class requires a DataSource object which can be injected either programmatically or
declaratively
HARSHIT CHOUDHARY
QUERY (SELECT)
 Simple Query for getting the number of rows
 Simple query using BindVariable
 Querying and populating a single domain object
HARSHIT CHOUDHARY
QUERY (SELECT)
 Querying and populating a number of domain objects:
HARSHIT CHOUDHARY
ROWMAPPER INTERFACE
 RowMapper interface is used for mapping rows of a ResultSet on a per row basis to a custom object
 It need to be implemented to provide the actual logic of mapping of ResultSet to a custom object
 Defines one method:
public Object mapRow(ResultSet rs, int rowNum) throws SQLException
 SQLException will be caught and handled by the calling JdbcTemplate
HARSHIT CHOUDHARY
UPDATING (INSERT/UPDATE/DELETE)
 Insert Query
 Delete Query
 Update Query
HARSHIT CHOUDHARY
NAMEDPARAMETER JDBC TEMPLATE
HARSHIT CHOUDHARY
OVERVIEW
 The class adds support for programming JDBC statements using named parameters instead of the placeholders (?)
 It wraps a JdbcTemplate and delegates much of its task to wrapped JdbcTemplate
 Usage Example of NamedParameterJdbcTemplate
 For giving more than one Parameter
HARSHIT CHOUDHARY
Named
Parameter Class to provide the values
for the named parameters
SQLPARAMETERSOURCE INTERFACE
 SQLParameterSource interface is a source of named parameter values to a
NamedJdbcParameterTemplate.
 Implementations of SQLParameterSource
 MapSqlParameterSource
 An adapter around a java.util.Map, where the keys are the parameter names and the values
are the parameter values
 BeanPropertySqlParameterSource
 This class wraps an arbitrary Java Bean and uses the properties of the wrapped JavaBean as
the source of named parameter values
HARSHIT CHOUDHARY
USING JAVABEAN TO PROVIDE PARAMETERS
HARSHIT CHOUDHARY
Class to provide Java
Bean parameters
CONTROLLING DATABASE CONNECTIONS
HARSHIT CHOUDHARY
DATASOURCE
 Spring obtains a connection to the database through DataSource
 A DataSource is a generalized connection factory
 It allows container to hide connection pooling and transaction management issues from the
application code
 DataSource can be obtained from JNDI or third party connection pool
implementation can also be provided
 Popular implementations are
 Apache Jakarta Commons DBCP
 C3P0
HARSHIT CHOUDHARY
DRIVERMANAGERDATASOURCE
 Spring’s DataSource implementation
 Doesnot provide pooling and will perform poorly when multiple requests for a connection are made
 Should be used only for testing purpose
 Configuring in xml file
HARSHIT CHOUDHARY

Spring jdbc

  • 1.
    DATA ACCESS WITHJDBC HARSHIT CHOUDHARY
  • 2.
    OUTLINE  Spring DataAccess  DAO Support  Introduction to Spring Framework JDBC  Using JDBC Core Classes  Controlling Database connections HARSHIT CHOUDHARY
  • 3.
    DAO SUPPORT INSPRING HARSHIT CHOUDHARY
  • 4.
    INTRODUCTION  The DataAccess Object (DAO) is a pattern to access the data of the database  DAO Support in Spring makes it easy to work with data access technologies in a consistent way  This allows to switch between different persistence technologies easily and without catching technology specific exceptions HARSHIT CHOUDHARY
  • 5.
    CONSISTENT EXCEPTION HIERARCHY Spring provides a convenient translation from technology-specific exception to its own exception class hierarchy.  These exceptions wrap the original exception so there is never risk to loose any information  DataAccessException is the root exception in Spring, which is a Runtime Exception and developers are not forced to handle the exception HARSHIT CHOUDHARY
  • 6.
  • 7.
    ANNOTATION FOR CONFIGURINGDAO CLASSES  @Repository  Provides exception translation  Allows component scanning support HARSHIT CHOUDHARY
  • 8.
    DATA ACCESS WITHJDBC HARSHIT CHOUDHARY
  • 9.
    OVERVIEW  Spring JDBCFramework allows developers to focus on core logic  Spring handles all the low level details and repetitive tasks like opening and closing of connections, exceptions, iteration of resultsets, transactions etc.  The table in next slide shows what actions spring take care of and which actions are responsibility of application developer HARSHIT CHOUDHARY
  • 10.
    SPRING JDBC –WHO DOES WHAT? HARSHIT CHOUDHARY Action Spring You Define connection parameters. X Open the connection. X Specify the SQL statement. X Declare parameters and provide parameter values X Prepare and execute the statement. X Set up the loop to iterate through the results (if any). X Do the work for each iteration. X Process any exception. X Handle transactions. X Close the connection, statement and resultset. X
  • 11.
    SPRING DATA ACCESSAPPROACHES  JdbcTemplate –  JdbcTemplate approach works for JDK 1.4 onwards and is widely used.  It is used internally in other three approaches.  handles the repetitive operations like opening and closing of connections and can execute select, insert, update statements, calls to stored procedures.  This class is thread safe.  NamedParameterJdbcTemplate –  supports the use of named parameters in place of traditional place holders ( ? ) and works with JDK 1.4 onwards.  SimpleJdbcTemplate-  Uses both JdbcTemplate and NamedParameterJdbcTemplate approaches and provides additional support of Java 5 features etc.  This approach requires JDK 5 onwards.  Deprecated in Spring 4.x onwards  SimpleJdbcInsert and SimpleJdbcCall –  utilizes the database metadata and hence reduces the configuration overhead. HARSHIT CHOUDHARY
  • 12.
    PACKAGE HIERARCHY  Theframework consists of 4 packages  Core  Contains JDBCTemplate class and its various call back interfaces Subpackages of Core  Simple  Contains the SimpleJdbcInsert and SimpleJdbcCall classes  Namedparam  Contains the NamedParameterJdbcTemplate class  Datasource  Utility class for easy DataSource access and various simple DataSource implementations  Object  Contains classes that represent RDBMS queries, updates and stored procedures as thread-safe reusable objects  Support  Provides SQLException translation functionality and some utility classes. Exceptions thrown during JDBC processing are translated to exceptions defined in org.springframework.dao package HARSHIT CHOUDHARY
  • 13.
    JDBCTEMPLATE CLASS  Centralclass in the JDBC core package  Handles creation and release of resources, and statement creation and execution  Executes SQL queries, update statements and stored procedure calls, perform iteration over ResultSet and extraction of returned parameter values.  Catches SQL Exceptions and translate them to related subclass of DataAccessException  JdbcTemplate class requires a DataSource object which can be injected either programmatically or declaratively HARSHIT CHOUDHARY
  • 14.
    QUERY (SELECT)  SimpleQuery for getting the number of rows  Simple query using BindVariable  Querying and populating a single domain object HARSHIT CHOUDHARY
  • 15.
    QUERY (SELECT)  Queryingand populating a number of domain objects: HARSHIT CHOUDHARY
  • 16.
    ROWMAPPER INTERFACE  RowMapperinterface is used for mapping rows of a ResultSet on a per row basis to a custom object  It need to be implemented to provide the actual logic of mapping of ResultSet to a custom object  Defines one method: public Object mapRow(ResultSet rs, int rowNum) throws SQLException  SQLException will be caught and handled by the calling JdbcTemplate HARSHIT CHOUDHARY
  • 17.
    UPDATING (INSERT/UPDATE/DELETE)  InsertQuery  Delete Query  Update Query HARSHIT CHOUDHARY
  • 18.
  • 19.
    OVERVIEW  The classadds support for programming JDBC statements using named parameters instead of the placeholders (?)  It wraps a JdbcTemplate and delegates much of its task to wrapped JdbcTemplate  Usage Example of NamedParameterJdbcTemplate  For giving more than one Parameter HARSHIT CHOUDHARY Named Parameter Class to provide the values for the named parameters
  • 20.
    SQLPARAMETERSOURCE INTERFACE  SQLParameterSourceinterface is a source of named parameter values to a NamedJdbcParameterTemplate.  Implementations of SQLParameterSource  MapSqlParameterSource  An adapter around a java.util.Map, where the keys are the parameter names and the values are the parameter values  BeanPropertySqlParameterSource  This class wraps an arbitrary Java Bean and uses the properties of the wrapped JavaBean as the source of named parameter values HARSHIT CHOUDHARY
  • 21.
    USING JAVABEAN TOPROVIDE PARAMETERS HARSHIT CHOUDHARY Class to provide Java Bean parameters
  • 22.
  • 23.
    DATASOURCE  Spring obtainsa connection to the database through DataSource  A DataSource is a generalized connection factory  It allows container to hide connection pooling and transaction management issues from the application code  DataSource can be obtained from JNDI or third party connection pool implementation can also be provided  Popular implementations are  Apache Jakarta Commons DBCP  C3P0 HARSHIT CHOUDHARY
  • 24.
    DRIVERMANAGERDATASOURCE  Spring’s DataSourceimplementation  Doesnot provide pooling and will perform poorly when multiple requests for a connection are made  Should be used only for testing purpose  Configuring in xml file HARSHIT CHOUDHARY