Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Spring JDBC Simplifying.

Slides:



Advertisements
Similar presentations
5 Copyright © 2005, Oracle. All rights reserved. Accessing the Database with Servlets.
Advertisements

Connecting to Databases. relational databases tables and relations accessed using SQL database -specific functionality –transaction processing commit.
1 juni 30, 2005 Spring JDBC. 2 juni 30, 2005 Doel Database acties Flexibel Gecontroleerd Productief.
Basic JDBC Celsina Bignoli What is JDBC Industry standard for database- connectivity between the Java language and a wide range of.
15-Jun-15 JDBC. JDBC is a Sun trademark It is often taken to stand for Java Database Connectivity Java is very standardized, but there are many versions.
Java Database Connectivity By: Abe Marji CS616. Agenda 1.Quick Review of Databases 2.What is SQL? 3.What is JDBC? 4.Advanced Functions of JDBC 5.Summary.
Clinton R. Begin 2 Dealing with Enterprise Database Challenges Featuring the Apache iBATIS Data Mapping Framework Clinton Begin
1 Java Database Connection (JDBC) There are many industrial-strength DBMS's commercially available in the market. Oracle, DB2, and Sybase are just a few.
UPortal Developers MIT August 2004 Persistence Strategy for uPortal 3 Mike DeSimone the r-smart group
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
Introduction to the Spring Framework Rajesh. Spring Mission Statement J2EE should be easier to use OO design is more important than any implementation.
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
1 KC Web & Java – 29 november 2005 – Design Patterns – The Template Method AJAX! KC Web & Java 29 november 2005.
Spring Data Access By, Srinivas Reddy.S
Stored procedures1 Stored procedures and functions Procedures and functions stored in the database.
CS 160: Software Engineering October 1 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
Spring Database Access Ojitha Kumanayaka Copyright © Virtusa, 2007.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
JDBC Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
Chapter 8 Databases.
Copyright  Oracle Corporation, All rights reserved. 6 Accessing a Database Using the JDBC API.
A Presentation By V AIBHAV S AHARAN Web-enHanced Information Management COMS E6125.
Copyright  Oracle Corporation, All rights reserved. 7 Accessing a Database Using SQLJ.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Forms with Spring MVC Handling Form.
Java Database Connectivity. Java and the database Database is used to store data. It is also known as persistent storage as the data is stored and can.
Copyright © 2002 ProsoftTraining. All rights reserved. Building Database Client Applications Using JDBC 2.0.
Creating competitive advantage Copyright © 2003 Enterprise Java Beans Presenter: Wickramanayake HMKSK Version:0.1 Last Updated:
JDBC Database Programming in Java Prepared by., Mrs.S.Amudha AP/SWE.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
Data Source Patterns.  Table Data Gateway  Row Data Gateway  Active Record  Data Mapper  Unit of Work  Identity Map.
JDBC CS 124. JDBC Java Database Connectivity Database Access Interface provides access to a relational database (by allowing SQL statements to be sent.
12/6/2015B.Ramamurthy1 Java Database Connectivity B.Ramamurthy.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
EXAMPLE I An application showing JDBC access to Cloudscape.
Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Spring MVC Essentials Getting started.
JDBC and SQLJ CIS 612 Spring JDBC JDBC is an API that enables database access from Java programs JDBC for DB access provides ◦ Portability across.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Testing Spring Applications Unit Testing.
Tasks Needed for MissionMapEditor Martin Q. Zhao September 18, 2010.
JDBC CS 260 Database Systems. Overview  Introduction  JDBC driver types  Eclipse project setup  Programming with JDBC  Prepared statements  SQL.
CSI 3125, Preliminaries, page 1 JDBC. CSI 3125, Preliminaries, page 2 JDBC JDBC stands for Java Database Connectivity, which is a standard Java API (application.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Data Access with Spring.
Basics of JDBC.
Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Overview of the Spring Framework Introducing.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
Advanced Java Session 5 New York University School of Continuing and Professional Studies.
Spring JDBC Dima Ionut Daniel. Contents What is Spring JDBC? Overview Spring JDBC Core SQL Exceptions Database Connection Batch Operations Handling BLOB/CLOB.
Fundamentals of MyBATIS
Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions and Spring MVC Buenos Aires, June 2009.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
ㅇ 데이터베이스 연동 지원 - 템플릿 클래스를 통한 데이터 접근 지원 - 의미있는 예외 클래스 제공 - 트랜잭션 처리 ㅇ Connection / PreparedStatement / ResultSet / try-catch 등 JDBC 중복 코드 제거 JDBC.
1. Writing a Java program to connect to SQL Server 2008 and Create a table Populate the table (insert data) Perform queries to retrieve information from.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
JDBC III IS Outline  Scrollable ResultSets  Updatable ResultSets  Prepared statements  Stored procedures.
Database Activity CEMC Steps 1. Verify Data Tools Platform is installed in Eclipse 2. Configure a Connection to Derby Create necessary table for.
DEPTT. OF COMP. SC & APPLICATIONS
CS3220 Web and Internet Programming Database Access with JDBC
Chengyu Sun California State University, Los Angeles
JDBC 15-Apr-18.
ATS Application Programming: Java Programming
JDBC 21-Aug-18.
HW#4 Making Simple BBS Using JDBC
Client Access, Queries, Stored Procedures, JDBC
JDBC 15-Nov-18.
Java Database Connectivity
Spring 프레임워크의 이해 5. Spring Abstract API.
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Spring JDBC Simplifying JDBC-based data access with Spring JDBC

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 2 Topics in this Session Problems with traditional JDBC –Results in redundant, error prone code –Leads to poor exception handling Spring’s JdbcTemplate –Configuration –Query execution –Working with result sets –Exception handling

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 3 Topics in this Session Problems with traditional JDBC –Results in redundant, error prone code –Leads to poor exception handling Spring’s JdbcTemplate –Configuration –Query execution –Working with result sets –Exception handling

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 4 Redundant, Error Prone Code public List findByLastName(String lastName) { List personList = new ArrayList(); Connection conn = null; String sql = “ select first_name, age from PERSON where last_name=? “ ; try { DataSource dataSource = DataSourceUtils.getDataSource(); conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, lastName); ResultSet rs = ps.executeQuery(); while (rs.next()) { String firstName = rs.getString( ” first_name “ ); int age = rs.getInt( “ age ” ); personList.add(new Person(firstName, lastName, age)); } } catch (Exception e) { /* ??? */ } finally { try { conn.close(); } catch (SQLException e) { /* ??? */ } } return personList; } public List findByLastName(String lastName) { List personList = new ArrayList(); Connection conn = null; String sql = “ select first_name, age from PERSON where last_name=? “ ; try { DataSource dataSource = DataSourceUtils.getDataSource(); conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, lastName); ResultSet rs = ps.executeQuery(); while (rs.next()) { String firstName = rs.getString( ” first_name “ ); int age = rs.getInt( “ age ” ); personList.add(new Person(firstName, lastName, age)); } } catch (Exception e) { /* ??? */ } finally { try { conn.close(); } catch (SQLException e) { /* ??? */ } } return personList; }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 5 Redundant, Error Prone Code public List findByLastName(String lastName) { List personList = new ArrayList(); Connection conn = null; String sql = "select first_name, age from PERSON where last_name=?"; try { DataSource dataSource = DataSourceUtils.getDataSource(); conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, lastName); ResultSet rs = ps.executeQuery(); while (rs.next()) { String firstName = rs.getString( “ first_name ” ); int age = rs.getInt( “ age ” ); personList.add(new Person(firstName, lastName, age)); } } catch (Exception e) { /* ??? */ } finally { try { conn.close(); } catch (SQLException e) { /* ??? */ } } return personList; } public List findByLastName(String lastName) { List personList = new ArrayList(); Connection conn = null; String sql = "select first_name, age from PERSON where last_name=?"; try { DataSource dataSource = DataSourceUtils.getDataSource(); conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, lastName); ResultSet rs = ps.executeQuery(); while (rs.next()) { String firstName = rs.getString( “ first_name ” ); int age = rs.getInt( “ age ” ); personList.add(new Person(firstName, lastName, age)); } } catch (Exception e) { /* ??? */ } finally { try { conn.close(); } catch (SQLException e) { /* ??? */ } } return personList; } The bold matters - the rest is boilerplate

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 6 public List findByLastName(String lastName) { List personList = new ArrayList(); Connection conn = null; String sql = "select first_name, age from PERSON where last_name=? “ ; try { DataSource dataSource = DataSourceUtils.getDataSource(); conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, lastName); ResultSet rs = ps.executeQuery(); while (rs.next()) { String firstName = rs.getString( ” first_name “ ); int age = rs.getInt( “ age ” ); personList.add(new Person(firstName, lastName, age)); } } catch (Exception e) { /* ??? */ } finally { try { conn.close(); } catch (SQLException e) { /* ??? */ } } return personList; } public List findByLastName(String lastName) { List personList = new ArrayList(); Connection conn = null; String sql = "select first_name, age from PERSON where last_name=? “ ; try { DataSource dataSource = DataSourceUtils.getDataSource(); conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, lastName); ResultSet rs = ps.executeQuery(); while (rs.next()) { String firstName = rs.getString( ” first_name “ ); int age = rs.getInt( “ age ” ); personList.add(new Person(firstName, lastName, age)); } } catch (Exception e) { /* ??? */ } finally { try { conn.close(); } catch (SQLException e) { /* ??? */ } } return personList; } Poor Exception Handling What can you do?

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 7 Topics in this session Problems with traditional JDBC –Results in redundant, error prone code –Leads to poor exception handling Spring’s JdbcTemplate –Configuration –Query execution –Working with result sets –Exception handling

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 8 Spring’s JdbcTemplate Greatly simplifies use of the JDBC API –Eliminates repetitive boilerplate code –Alleviates common causes of bugs –Handles SQLExceptions properly Without sacrificing power –Provides full access to the standard JDBC constructs

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 9 JdbcTemplate in a Nutshell Acquisition of the connection Participation in the transaction Execution of the statement Processing of the result set Handling any exceptions Release of the connection int count = jdbcTemplate.queryForInt( “SELECT COUNT(*) FROM CUSTOMER”); int count = jdbcTemplate.queryForInt( “SELECT COUNT(*) FROM CUSTOMER”); All handled by Spring

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 10 JdbcTemplate Approach Overview List results = jdbcTemplate.query(someSql, new RowMapper() { public Object mapRow(ResultSet rs, int row) { // map the current row to an object } }); class JdbcTemplate { public List query(sql, rowCallback) { try { // acquire connection // prepare statement // execute statement // for each row in the result set results.add(rowCallback.mapRow(rs, rowNumber)); return results; } catch (SQLException e) { // convert to root cause exception } finally { // release connection } }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 11 Creating a JdbcTemplate Requires a DataSource Create a template once and re-use it –Do not create one for each use –Thread safe after construction JdbcTemplate template = new JdbcTemplate(dataSource);

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 12 When to use JdbcTemplate Useful standalone –Anytime JDBC is needed –In utility or test code –To clean up messy legacy code Useful for implementing a repository in a layered application –Also known as a data access object (DAO)

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 13 Steps to implementing a JDBC-based repository 1.Create a new class –Typically implementing a data access interface you define 2.Implement data access methods using the JdbcTemplate or SimpleJdbcTemplate 3.Unit test the data access behavior 4.Integrate the repository into your application Where it will typically participate in application- driven transactions

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 14 Creating a JDBC-based Repository class Spring provides two support classes you may extend from –Extend JdbcDaoSupport on Java 1.4 –Extend SimpleJdbcDaoSupport on Java 5.0 or greater After extending you inherit a JdbcTemplate you configure by injecting a DataSource

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 15 Implementing a JDBC-based Repository - Java 1.4 public class JdbcCustomerRepository implements CustomerRepository { private JdbcTemplate jdbcTemplate; private JdbcCustomerRepository(DataSource ds) { this.jdbcTemplate = new JdbcTemplate(dataSource); } public int getCustomerCount() { String sql = “select count(*) from customer”; return jdbcTemplate.queryForInt(sql); } public class JdbcCustomerRepository implements CustomerRepository { private JdbcTemplate jdbcTemplate; private JdbcCustomerRepository(DataSource ds) { this.jdbcTemplate = new JdbcTemplate(dataSource); } public int getCustomerCount() { String sql = “select count(*) from customer”; return jdbcTemplate.queryForInt(sql); }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 16 Implementing a JDBC-based Repository - Java 5.0 or > public class JdbcCustomerRepository implements CustomerRepository { private SimpleJdbcTemplate jdbcTemplate; private JdbcCustomerRepository(DataSource ds) { this.jdbcTemplate = new SimpleJdbcTemplate(dataSource); } public int getCustomerCountOlderThan(int age) { String sql = “select count(*) from customer where age > ?”; return jdbcTemplate.queryForInt(sql, age); } public class JdbcCustomerRepository implements CustomerRepository { private SimpleJdbcTemplate jdbcTemplate; private JdbcCustomerRepository(DataSource ds) { this.jdbcTemplate = new SimpleJdbcTemplate(dataSource); } public int getCustomerCountOlderThan(int age) { String sql = “select count(*) from customer where age > ?”; return jdbcTemplate.queryForInt(sql, age); }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 17 Integrating a Repository into an Application <bean id=“customerRepository” class=“example.customer.JdbcCustomerRepository”> <bean id=“customerRepository” class=“example.customer.JdbcCustomerRepository”> Configure the repository’s DataSourceInject the repository into application services

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 18 A Word on JdbcDaoSupport Spring has a convenient super class you can extend –Provides a setDataSource() method –Instantiates a (Simple)JdbcTemplate for you –Get access to the template using getJdbcTemplate() Preferably use constructor-injection and code up your own class instead of using the JdbcDaoSupport class –Support class uses setter injection: less concise –Support class does not work well

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 19 A Word on JdbcTemplate versus SimpleJdbcTemplate SimpleJdbcTemplate is not only for Java 5 and above –Some infrequently used functionality has been removed If you need more control, use the getJdbcOperations() method to get to the underlying JdbcTemplate, which has all the power you want. Stick to using SimpleJdbcTemplate where possible

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 20 Querying with JdbcTemplate JdbcTemplate can query for –Simple types (int, long, String) –Generic Maps –Domain Objects

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 21 Querying for Simple Java Types (1) Query with no bind variables public int getPersonCount() { String sql = “select count(*) from PERSON”; return getJdbcTemplate().queryForInt(sql); } public int getPersonCount() { String sql = “select count(*) from PERSON”; return getJdbcTemplate().queryForInt(sql); }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 22 Querying for Simple Java Types (2) Query with a bind variable public int getCountOfPersonsOlderThan(int age) { return getJdbcTemplate().queryForInt( “select count(*) from PERSON where age > ?”, new Object[] { new Integer(age) }); } public int getCountOfPersonsOlderThan(int age) { return getJdbcTemplate().queryForInt( “select count(*) from PERSON where age > ?”, new Object[] { new Integer(age) }); }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 23 Querying With SimpleJdbcTemplate Use SimpleJdbcTemplate if running on Java 5 or > public int getCountOfPersonsOlderThan(int age) { return getSimpleJdbcTemplate().queryForInt( “select count(*) from PERSON where age > ?”, age); } public int getCountOfPersonsOlderThan(int age) { return getSimpleJdbcTemplate().queryForInt( “select count(*) from PERSON where age > ?”, age); } No need for new Object[] { new Integer(age) }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 24 Generic Queries JdbcTemplate can return each row of a ResultSet as a Map When expecting a single row –Use queryForMap(..) When expecting multiple rows –Use queryForList(..) Useful for reporting, testing, and ‘window-on- data’ use cases

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 25 Querying for Generic Maps (1) Query for a single row returns: Map { ID=1, FIRST_NAME= “ John ”, LAST_NAME= “ Doe ” } public Map getPersonInfo(int id) { String sql = “select * from PERSON where id=?”; return getJdbcTemplate().queryForMap(sql, id); } public Map getPersonInfo(int id) { String sql = “select * from PERSON where id=?”; return getJdbcTemplate().queryForMap(sql, id); }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 26 Querying for Generic Maps (2) Query for multiple rows returns: List { 0 - Map { ID=1, FIRST_NAME= “ John ”, LAST_NAME= “ Doe ” } 1 - Map { ID=2, FIRST_NAME= “ Jane ”, LAST_NAME= “ Doe ” } 2 - Map { ID=3, FIRST_NAME= “ Junior ”, LAST_NAME= “ Doe ” } } public List getAllPersonInfo() { String sql = “select * from PERSON”; return getJdbcTemplate().queryForList(sql); } public List getAllPersonInfo() { String sql = “select * from PERSON”; return getJdbcTemplate().queryForList(sql); }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 27 Domain Object Queries Often it is useful to map relational data into domain objects –e.g. a ResultSet to an Account Spring’s JdbcTemplate supports this using a callback approach

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 28 Querying for Domain Objects (1) Query for a single row public Person getPerson(int id) { return (Person)getJdbcTemplate().queryForObject( “select first_name, last_name from PERSON where id=?”, new Object[] { new Long(id) }, new PersonMapper()); } public Person getPerson(int id) { return (Person)getJdbcTemplate().queryForObject( “select first_name, last_name from PERSON where id=?”, new Object[] { new Long(id) }, new PersonMapper()); } class PersonMapper implements RowMapper { public Object mapRow(ResultSet rs, int i) { return new Person(rs.getString(1), rs.getString(2)); } class PersonMapper implements RowMapper { public Object mapRow(ResultSet rs, int i) { return new Person(rs.getString(1), rs.getString(2)); } Maps rows to Person objects

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 29 Querying for Domain Objects (2) Query for multiple rows public List getAllPersons() { return getJdbcTemplate().query( “select first_name, last_name from PERSON”, new PersonMapper()); } public List getAllPersons() { return getJdbcTemplate().query( “select first_name, last_name from PERSON”, new PersonMapper()); } class PersonMapper implements RowMapper { public Object mapRow(ResultSet rs, int i) { return new Person(rs.getString(1), rs.getString(2)); } class PersonMapper implements RowMapper { public Object mapRow(ResultSet rs, int i) { return new Person(rs.getString(1), rs.getString(2)); } Same row mapper can be used

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 30 Querying for a Single Domain Object with SimpleJdbcTemplate SimpleJdbcTemplate benefits from generics public Person getPerson(int id) { return getSimpleJdbcTemplate().queryForObject( “select first_name, last_name from PERSON where id=?”, new PersonMapper(), id); } public Person getPerson(int id) { return getSimpleJdbcTemplate().queryForObject( “select first_name, last_name from PERSON where id=?”, new PersonMapper(), id); } class PersonMapper implements ParameterizedRowMapper { public Person mapRow(ResultSet rs, int i) { return new Person(rs.getString(1), rs.getString(2)); } class PersonMapper implements ParameterizedRowMapper { public Person mapRow(ResultSet rs, int i) { return new Person(rs.getString(1), rs.getString(2)); } Parameterizes return type No need to cast

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 31 Querying for Multiple Domain Objects with SimpleJdbcTemplate public List getAllPersons() { return getSimpleJdbcTemplate().query( “select first_name, last_name from PERSON”, new PersonMapper()); public List getAllPersons() { return getSimpleJdbcTemplate().query( “select first_name, last_name from PERSON”, new PersonMapper()); class PersonMapper implements ParameterizedRowMapper { public Person mapRow(ResultSet rs, int i) { return new Person(rs.getString(1), rs.getString(2)); } class PersonMapper implements ParameterizedRowMapper { public Person mapRow(ResultSet rs, int i) { return new Person(rs.getString(1), rs.getString(2)); } No need to cast

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 32 RowCallbackHandler Spring provides a simpler RowCallbackHandler interface when there is no return object –Streaming rows to a file –Filtering rows before adding to a Collection public interface RowCallbackHandler { void processRow(ResultSet rs) throws SQLException; } public interface RowCallbackHandler { void processRow(ResultSet rs) throws SQLException; }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 33 Using a RowCallbackHandler public class JdbcOrderRepository { public void generateReport() { // select all orders for a full report getJdbcTemplate().query(“select...from order o, item i”, new OrderReportWriter()); } public class JdbcOrderRepository { public void generateReport() { // select all orders for a full report getJdbcTemplate().query(“select...from order o, item i”, new OrderReportWriter()); } class OrderReportWriter implements RowCallbackHandler { public void processRow(ResultSet rs) throws SQLException { // stream row to a file } class OrderReportWriter implements RowCallbackHandler { public void processRow(ResultSet rs) throws SQLException { // stream row to a file }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 34 ResultSetExtractor Spring provides a ResultSetExtractor interface for mapping an entire ResultSet to an object public interface ResultSetExtractor { Object extractData(ResultSet rs) throws SQLException, DataAccessException; } public interface ResultSetExtractor { Object extractData(ResultSet rs) throws SQLException, DataAccessException; }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 35 Using a ResultSetExtractor public class JdbcOrderRepository { public Order findByConfirmationNumber(String number) { // execute an outer join between order and item tables return (Order) getJdbcTemplate().query( “select...from order o, item i...conf_id = ?”, new Object[] { number }, new OrderExtractor()); } public class JdbcOrderRepository { public Order findByConfirmationNumber(String number) { // execute an outer join between order and item tables return (Order) getJdbcTemplate().query( “select...from order o, item i...conf_id = ?”, new Object[] { number }, new OrderExtractor()); } class OrderExtractor implements ResultSetExtractor { public Object extractData(ResultSet rs) throws SQLException { // create an Order object from multiple rows } class OrderExtractor implements ResultSetExtractor { public Object extractData(ResultSet rs) throws SQLException { // create an Order object from multiple rows }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 36 Summary of Callback Interfaces RowMapper –Best choice when each row of a ResultSet maps to a domain object RowCallbackHandler –Best choice when no value should be returned from the callback method ResultSetExtractor –Best choice when multiple rows of a ResultSet map to a domain object

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 37 Inserts and Updates (1) Inserting a new row public int insertPerson(Person person) { return getSimpleJdbcTemplate().update( “insert into PERSON (first_name, last_name, age)” + “values (?, ?, ?)”, person.getFirstName(), person.getLastName(), person.getAge()); } public int insertPerson(Person person) { return getSimpleJdbcTemplate().update( “insert into PERSON (first_name, last_name, age)” + “values (?, ?, ?)”, person.getFirstName(), person.getLastName(), person.getAge()); }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 38 Inserts and Updates (2) Updating an existing row public int updateAge(Person person) { return getSimpleJdbcTemplate().update( “update PERSON set age=? where id=?”, person.getAge(), person.getId()); } public int updateAge(Person person) { return getSimpleJdbcTemplate().update( “update PERSON set age=? where id=?”, person.getAge(), person.getId()); }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 39 SQLException Handling SQLExceptions are often handled inconsistently in many applications Using the JdbcTemplate ensures SQLExceptions are handled properly

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 40 SQLException Handling Issues Hard to determine cause of failure –Must read a vendor-specific error code SQLException is a leaky abstraction –As a checked exception a SQLException must propagate if it is not caught –Leads to one of two things: “Catch and wrap” Being swallowed

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 41 Spring SQLException Handling SQLExceptions are handled consistently –Resources are always released properly Generic SQLExceptions are translated to root cause DataAccessExceptions –Provides consistency across all database vendors –Frees you from your own catch-and-wrap approach –Enables selective handling by type of failure –Exceptions always propagate if not caught

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 42 Spring DataAccessException Hierarchy (subset) DataRetrievalFailureException DataAccessResourceFailureException CleanupFailureDataAccessException InvalidDataAccessApiUsageException InvalidDataAccessResourceUsageException IncorrectUpdateSemanticsDataAccessException TypeMismatchDataAccessException OptimisticLockingFailureException ObjectRetrievalFailureException DataAccessException UncategorizedDataAccessException DataIntegrityViolationException DeadlockLoserDataAccessException ObjectOptimisticLockingFailureException

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Lab Introduction to Spring JDBC