SlideShare ist ein Scribd-Unternehmen logo
1 von 43
Simple JDBC with
                                                  Spring 2.5

                                                            Thomas Risberg
                                                            SpringSource Inc.




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Introduction


         • Background - COBOL programmer, Oracle
           DBA, J2EE developer, Spring developer,
           SpringSource employee
         • Committer on the Spring Framework
           project since 2003, supporting the JDBC
           and Data Access code
         • Co-author of “Professional Java
           Development with the Spring Framework”
           from Wrox

Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   2
Agenda


         • JDBC development doesn’t have to be
           difficult
         • When is JDBC more appropriate than an
           ORM solution
         • Look at new Spring 2.5 JDBC features
         • A few other 2.5 features that are handy for
           data access development and testing




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   3
Yuck!!
   public class JdbcDaoImpl {
           public int getCustomerCount() {
                Connection conn = null;
                Statement stmt = null;
                ResultSet rs = null;
                int count = 0;
                Properties properties = new Properties();
                try {
                      properties.load(new FileInputStream("jdbc.properties"));

                                                                                                                        Using
                } catch (IOException e) {
                      throw new MyDataAccessException(“I/O Error”, e);
                }
                try {


                                                                                                                       straight
                      Class.forName(properties.getProperty("driverClassName"));
                      conn = DriverManager.getConnection(properties.getProperty("url"), properties);
                      stmt = conn.createStatement();
                      rs = stmt.executeQuery("select count(*) from customers");


                                                                                                                     JDBC code
                      if (rs.next()) {
                            count = rs.getInt(1);
                      }
                }
                catch (ClassNotFoundException e) {
                      throw new MyDataAccessException(“JDBC Error”, e);
                }
                catch (SQLException se) {
                      throw new MyDataAccessException(“JDBC Error”, se);
                }
                finally {
                      if (rs != null) {
                            try {
                                  rs.close();
                            }
                            catch (SQLException ignore) {}
                      }
                      if (stmt != null) {
                            try {
                                  stmt.close();
                            }
                            catch (SQLException ignore) {}
                      }
                      if (conn != null) {
                            try {
                                  conn.close();
                            }
                            catch (SQLException ignore) {}
                      }
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
                }                                                                                                                 4
                return count;
           }
    }
Much better!
@Repository
public class SpringDaoImpl {
    private JdbcTemplate jdbcTemplate;

         @Autowired
         public void setDataSource(DataSource dataSource) {
             this.jdbcTemplate = new JdbcTemplate(dataSource);
         }

         public int getCustomerCount() {
             return jdbcTemplate.queryForInt("select count(*) from customers");
         }
}
                                  <context:property-placeholder location="classpath:jdbc.properties"/>
                                  <context:annotation-config/>
                                  <context:component-scan base-package="com.springsource.data.sample"/>

                                  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
                                        destroy-method="close">
                                      <property name="driverClassName" value="${db.driverClassName}"/>
                                      <property name="url" value="${db.url}"/>
                                      <property name="username" value="${db.username}"/>
                                      <property name="password" value="${db.password}"/>
                                  </bean>


Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   5
Who does what?


            Task                                                                                                     Spring   You

            Connection Management                                                                                      √
            SQL                                                                                                                √
            Statement Management                                                                                       √
            ResultSet Management                                                                                       √
            Row Data Retrieval                                                                                                 √
            Parameter Declaration                                                                                              √
            Parameter Setting                                                                                          √
            Transaction Management                                                                                     √
            Exception Handling                                                                                         √



Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.                  6
Plain JDBC vs. Spring JDBC

                                           JDBC                                                                      Spring
              DriverManager /                                                                 DataSource
              DataSource
              Statement /                                                                     JdbcTemplate /
              PreparedStatement /                                                             SimpleJdbcTemplate,
              CallableStatement                                                               SimpleJdbcCall,
                                                                                              SimpleJdbcInsert
                                                                                              MappingSqlQuery /
                                                                                              StoredProcedure
              ResultSet / RowSet                                                              POJOs / List of POJOs or
                                                                                              Maps / SqlRowSet

Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.            7
Exception Translation

 SQLException is translated to a more expressive sub-class of DataAccessException like
 DataIntegrityViolationException or CannotAcquireLockException. This is translation is
 based on SQL Error codes forts and then SQL State codes. Translation is controlled by
 entries in sql-error-codes.xml.
             sql-error-codes.xml
              
             <bean id="MySQL" class="org.springframework.jdbc.support.SQLErrorCodes">
              
             
     <property name="badSqlGrammarCodes">
              
             
     
      <value>1054,1064,1146</value>
              
             
     </property>
              
             
     <property name="dataAccessResourceFailureCodes">
              
             
     
      <value>1</value>
              
             
     </property>
              
             
     <property name="dataIntegrityViolationCodes">
              
             
     
      <value>1062</value>
              
             
     </property>
              
             
     <property name="cannotAcquireLockCodes">
              
             
     
      <value>1205</value>
              
             
     </property>
              
             
     <property name="deadlockLoserCodes">
              
             
     
      <value>1213</value>
              
             
     </property>
              
             </bean>



Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   8
Jobs?




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   9
When should you use JDBC?


         • Trivial domain model, few tables
         • Complex queries reading and modifying
           multiple tables
         • Stored procedures, db specific data
           types
         • Bulk operations
         • Tasks where you are not mapping
           relational data to an object graph


Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   10
Mix JDBC and ORM


         • It’s not an either or situation
         • You can mix ORM access with JDBC
         • Stored procedures are typically better
           supported with JDBC
         • ORM and JDBC share transaction
           management - can participate in same
           transaction
         • Remember to flush ORM session/entity
           manager before JDBC access

Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   11
Simple Example


         • Single Table (MySQL)
                    CREATE
                      TABLE customer
                      (
                        id int(11) NOT NULL AUTO_INCREMENT,
                        name varchar(50),
                        customer_number varchar(50),
                        birth_date date,
                        PRIMARY KEY USING BTREE (id)
                      )
                      ENGINE= InnoDB DEFAULT CHARSET= latin1


Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   12
The Customer class

                                      package com.springsource.data.sample.domain;

                                      import java.util.Date;

                                      public class Customer
                                      {
                                          private Long id;

                                                private String name;

                                                private String customerNumber;

                                                private Date birthDate;

                                                // getters and setters //
                                      	
                                      }




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   13
DAO/Repository Interface

                                package com.springsource.data.sample.repository;

                                import java.util.List;

                                import com.springsource.data.sample.domain.Customer;

                                public interface CustomerRepository {

                                	                    void add(Customer customer);
                                	
                                	                    Customer findById(Long id);
                                	
                                	                    void save(Customer customer);

                                	                    List<Customer> findAll();
                                	
                                }




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   14
Spring 2.5 and SimpleJdbc

   • Spring 2.5 features for Simple JDBC:
             –      SimpleJdbcTemplate (named parameter support)
             –      SimpleJdbcInsert
             –      SimpleJdbcCall
             –      Annotation configuration
                        • @Repository, @Service, @Component
                        • @Autowired, @Qualifier
             – JUnit 4 support
                        • @RunWith(SpringJUnit4ClassRunner.class)
                        • @ContextConfiguration
                        • @Transactional @Test


Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   15
Simple Queries



 Customer customer = simpleJdbcTemplate.queryForObject(
     "select id, name, customer_number, birth_date from customer where id = ?",
     ParameterizedBeanPropertyRowMapper.newInstance(Customer.class),
     id);




                List<Customer> customerList = simpleJdbcTemplate.query(
                    "select id, name, customer_number, birth_date from customer",
                    ParameterizedBeanPropertyRowMapper.newInstance(Customer.class));




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   16
Simple Updates


                                                                                               named parameters

simpleJdbcTemplate.update(
    "update customer set name = :name, birth_date = :birth_date where id = :id",
	        new BeanPropertySqlParameterSource(customer));




                                              source of values to match parameters



Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   17
Passing in parameter values


         • java.util.Map
                   – simple but doesn’t provide type info
         • MapSqlParameterSource
                   – provides option of passing in SQL type
                          values.addValue("birth_date", customer.getBirthdate(), Types.DATE)

         • BeanPropertySqlParameterSource
                   – automatic mapping of property values from a
                     JavaBean to parameters of same name
                   – provides option of specifying SQL type
                          values.registerSqlType("birth_date", Types.DATE)




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   18
Mapping results


         • ParameterizedRowMapper
                   – provides for customized mapping from
                     results data to domain class
         • ParameterizedBeanPropertyRowMapper
                   – automatic mapping from results data to a
                     JavaBean. Column names are mapped to
                     properties. (Use column aliases if names
                     don’t match)




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   19
Live Code




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   20
Insert data and access
  generated keys

         • Traditionally a bit tricky - need to use
           PreparedStatementCreator and a
           KeyHolder
         • What if -
                   – you knew the name of the table
                   – the name and type of the columns


         • Maybe the JDBC framework could
           provide the rest ...

Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   21
Database Metadata
  customer table

                                       column name




                                                                                     parameter type




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   22
SimpleJdbcInsert


             private SimpleJdbcInsert insertCustomer;
             ...
             this.insertCustomer = new SimpleJdbcInsert(dataSource)
              	       .withTableName("customer")
              	       .usingGeneratedKeyColumns("id");




                                  Number newId =
                                  	        insertCustomer.executeAndReturnKey(
                                  	        	        new BeanPropertySqlParameterSource(customer));
                                  customer.setId(newId.longValue());




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   23
SimpleJdbcInsert


         • Simplifies insert operations
         • Uses table metadata to provide
           automatic column configuration
         • Option to provide explicit configuration
         • Supports auto generated keys in a
           database independent fashion
         • Supports batch inserts of arrays of Maps
           or SqlParameters


Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   24
Live Code




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   25
Stored Procedures


         • Are they really that hard to use?
         • What if -
                   – you knew the name of the procedure
                   – the name and type of the parameters


         • Maybe the JDBC framework could
           provide the rest ...




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   26
generate_customer_no
  declaration


        CREATE PROCEDURE generate_customer_no(
          IN in_prefix varchar(10),
          OUT out_customer_no varchar(50))
        BEGIN
          SELECT CONCAT(in_prefix, '.',
                (RAND() * 10000000))
             INTO out_customer_no;
        END




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   27
Database Metadata
  generate_customer_no

                                                                                                                in or out
                                        procedure name




    column/parameter name                                                                                               SQL type




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.                 28
SimpleJdbcCall
  generate_customer_no


              private SimpleJdbcCall generateCustomerNumberCall;
              ...
              this.generateCustomerNumberCall = new SimpleJdbcCall(dataSource)
              	        .withProcedureName("generate_customer_no");




                        String customerNumber = generateCustomerNumberCall.executeObject(
                        	        String.class,
                        	        Collections.singletonMap("in_prefix", "XYZ"));




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   29
SimpleJdbcCall
   DEBUG output
DEBUG [org.springframework.jdbc.core.simple.SimpleJdbcCall] - JdbcCall call not compiled before execution - invoking compile
DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataProviderFactory] - Using
org.springframework.jdbc.core.metadata.GenericCallMetaDataProvider
DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataProvider] - Retrieving metadata for null/null/generate_customer_no
DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataProvider] - Retrieved metadata: in_prefix 1 12 VARCHAR false
DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataProvider] - Retrieved metadata: out_customer_no 4 12 VARCHAR
false
DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataContext] - Added metadata in parameter for: in_prefix
DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataContext] - Added metadata out parameter for: out_customer_no
DEBUG [org.springframework.jdbc.core.simple.SimpleJdbcCall] - Compiled stored procedure. Call string is [{call
generate_customer_no(?, ?)}]
DEBUG [org.springframework.jdbc.core.simple.SimpleJdbcCall] - SqlCall for procedure [generate_customer_no] compiled
DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataContext] - Matching {in_prefix=XYZ} with
{out_customer_no=out_customer_no, in_prefix=in_prefix}
DEBUG [org.springframework.jdbc.core.simple.SimpleJdbcCall] - The following parameters are used for call {call
generate_customer_no(?, ?)} with: {in_prefix=XYZ}
DEBUG [org.springframework.jdbc.core.simple.SimpleJdbcCall] - 1: in_prefix SQL Type 12 Type Name null
org.springframework.jdbc.core.SqlParameter
DEBUG [org.springframework.jdbc.core.simple.SimpleJdbcCall] - 2: out_customer_no SQL Type 12 Type Name null
org.springframework.jdbc.core.SqlOutParameter
DEBUG [org.springframework.jdbc.core.JdbcTemplate] - Calling stored procedure [{call generate_customer_no(?, ?)}]
DEBUG [org.springframework.jdbc.core.StatementCreatorUtils] - Setting SQL statement parameter value: column index 1,
parameter value [XYZ], value class [java.lang.String], SQL type 12
DEBUG [org.springframework.jdbc.core.JdbcTemplate] - CallableStatement.execute() returned 'false'
DEBUG [org.springframework.jdbc.core.JdbcTemplate] - CallableStatement.getUpdateCount() returned 0
INFO [org.springframework.jdbc.core.JdbcTemplate] - Added default SqlReturnUpdateCount parameter named #update-count-1
DEBUG [org.springframework.jdbc.core.JdbcTemplate] - CallableStatement.getUpdateCount() returned -1



 Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.     30
SimpleJdbcCall


         • Simplifies access to stored procedures
         • Any database can be used with explicit
           parameter configuration
         • Supported databases provides automatic
           parameter configuration:
                   –      Apache Derby
                   –      DB2
                   –      MySQL
                   –      Microsoft SQL Server
                   –      Oracle
                   –      Sybase

Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   31
Live Code




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   32
Q&A



                                                  Questions?

                             thomas.risberg@springsource.com




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   33
Source Code
                  Customer.java
                   package com.springsource.data.sample.domain;

                   import java.util.Date;

                   public class Customer
                   {
                       private Long id;

                           private String name;

                           private String customerNumber;

                           private Date birthDate;

                           public Long getId() {
                               return id;
                           }

                           public void setId(Long id) {
                               this.id = id;
                           }


                  (continued)


Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   34
Source Code
                  Customer.java (continued)
                           public String getName() {
                               return name;
                           }

                           public void setName(String name) {
                               this.name = name;
                           }

                           public String getCustomerNumber() {
                               return customerNumber;
                           }

                           public void setCustomerNumber(String customerNumber) {
                               this.customerNumber = customerNumber;
                           }

                           public Date getBirthDate() {
                               return birthDate;
                           }

                           public void setBirthDate(Date birthDate) {
                               this.birthDate = birthDate;
                           }

                    }

Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   35
Source Code
     SimpleCustomerRepository.java
      package com.springsource.data.sample.repository;

      import java.util.Collections;
      import java.util.List;

      import javax.sql.DataSource;

      import       org.springframework.beans.factory.annotation.Autowired;
      import       org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
      import       org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
      import       org.springframework.jdbc.core.simple.SimpleJdbcCall;
      import       org.springframework.jdbc.core.simple.SimpleJdbcInsert;
      import       org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
      import       org.springframework.stereotype.Repository;

      import com.springsource.data.sample.domain.Customer;



      @Repository
      public class SimpleCustomerRepository implements CustomerRepository {

             private SimpleJdbcTemplate simpleJdbcTemplate;

             private SimpleJdbcInsert insertCustomer;

             private SimpleJdbcCall generateCustomerNumberCall;

      (continued)
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   36
Source Code
   SimpleCustomerRepository.java (continued)
           @Autowired
           public void init(DataSource dataSource) {

                  this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);

                  this.insertCustomer = new SimpleJdbcInsert(dataSource)
                      .withTableName("customer")
                      .usingGeneratedKeyColumns("id");
           	
                  this.generateCustomerNumberCall = new SimpleJdbcCall(dataSource)
                      .withProcedureName("generate_customer_no");

           }

           public void add(Customer customer) {
               String customerNumber = generateCustomerNumberCall.executeObject(
                       String.class,
                       Collections.singletonMap("in_prefix", "XYZ"));
               customer.setCustomerNumber(customerNumber);
               Number newId =
                   insertCustomer.executeAndReturnKey(
                           new BeanPropertySqlParameterSource(customer));
                   customer.setId(newId.longValue());
           }

  (continued)

Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   37
Source Code
   SimpleCustomerRepository.java (continued)
           public Customer findById(Long id) {
               Customer customer = simpleJdbcTemplate.queryForObject(
                      "select id, name, customer_number, birth_date from customer where id = ?",
                       ParameterizedBeanPropertyRowMapper.newInstance(Customer.class),
                       id);
               return customer;
           }
    	
           public void save(Customer customer) {
               simpleJdbcTemplate.update(
                      "update customer set name = :name, birth_date = :birthDate where id = :id",
                       new BeanPropertySqlParameterSource(customer));
           }

           public List<Customer> findAll() {
                List<Customer> customerList = simpleJdbcTemplate.query(
                   "select id, name, customer_number, birth_date from customer",
                   ParameterizedBeanPropertyRowMapper.newInstance(Customer.class));
                return customerList;
           }

    }




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   38
Source Code
     CustomerRepository4Tests.java
      package com.springsource.data.sample.repository;

      import static org.junit.Assert.assertEquals;
      import static org.junit.Assert.assertNotNull;
      import static org.junit.Assert.assertTrue;

      import java.util.Date;
      import java.util.List;

      import javax.sql.DataSource;

      import       org.junit.Before;
      import       org.junit.Test;
      import       org.junit.runner.RunWith;
      import       org.springframework.beans.factory.annotation.Autowired;
      import       org.springframework.jdbc.core.JdbcTemplate;
      import       org.springframework.test.context.ContextConfiguration;
      import       org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
      import       org.springframework.transaction.annotation.Transactional;

      import com.springsource.data.sample.domain.Customer;



      (continued)



Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   39
Source Code
     CustomerRepository4Tests.java (continued)
      @RunWith(SpringJUnit4ClassRunner.class)
      @ContextConfiguration
      public class CustomerRepository4Tests {

             @Autowired
             private CustomerRepository customerRepository;

             @Autowired
             private DataSource dataSource;

             @Before
             public void onSetUpInTransaction() throws Exception {
                 // Load test data
                 JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
                 jdbcTemplate.execute("delete from customer");
                 jdbcTemplate.execute(
                         "insert into customer (id, customer_number, name, birth_date) " +
                         "values (1, 'Z.12345.67890', 'Bubba', '1990-02-03')");
                 jdbcTemplate.execute(
                         "insert into customer (id, customer_number, name, birth_date) " +
                         "values (2, 'Z.12345.98765', 'Mary', '1988-01-31')");
             }


    (continued)



Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   40
Source Code
     CustomerRepository4Tests.java (continued)
             @Transactional @Test
             public void testFindAll() {
                 List<Customer> l = customerRepository.findAll();
                 assertEquals("Wrong number of customers returned", 2, l.size());
             }

             @Transactional @Test
             public void testFindById() {
                 Customer c = customerRepository.findById(2L);
                 assertNotNull("Customer not found", c);
             }

             @Transactional @Test
             public void testAddCustomer() {
                 Customer c = new Customer();
                 c.setBirthDate(new Date(19829922L));
                 c.setName("Sven");
                 customerRepository.add(c);
                 assertNotNull("Customer id not assigned", c.getId());
                 assertTrue("Bad customer id", 3 <= c.getId());
                 assertNotNull("Customer number not assigned", c.getCustomerNumber());
             }


    (continued)



Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   41
Source Code
     CustomerRepository4Tests.java (continued)
             @Transactional @Test
             public void testUpdateCustomer() {
                 Customer c = customerRepository.findById(2L);
                 c.setBirthDate(new Date(19829933L));
                 customerRepository.save(c);
                 Customer c2 = customerRepository.findById(2L);
                 assertEquals("BirthDate not updated", 18000000L, c2.getBirthDate().getTime());
             }
      }




Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   42
Source Code
     CustomerRepository4Tests-context.xml
      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:p="http://www.springframework.org/schema/p"
          xmlns:context="http://www.springframework.org/schema/context"
          xmlns:tx="http://www.springframework.org/schema/tx"
          xsi:schemaLocation="http://www.springframework.org/schema/beans
                  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
              http://www.springframework.org/schema/tx
                  http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
              http://www.springframework.org/schema/context
                  http://www.springframework.org/schema/context/spring-context-2.5.xsd">

             <context:annotation-config/>

             <context:component-scan base-package="com.springsource.data.sample"/>

             <context:property-placeholder location="classpath:jdbc.properties"/>

             <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
                 p:driverClassName="${jdbc.driverClassName}"
                 p:url="${jdbc.url}"
                 p:username="${jdbc.username}"
                 p:password="${jdbc.password}"/>

             <tx:annotation-driven/>

             <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
                 p:dataSource-ref="dataSource"/>

      </beans>


Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.    43

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Oracle 10g
Oracle 10gOracle 10g
Oracle 10g
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
 
Hibernate
Hibernate Hibernate
Hibernate
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
 
Spring Data in 10 minutes
Spring Data in 10 minutesSpring Data in 10 minutes
Spring Data in 10 minutes
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
 
Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentation
 
Jdbc
JdbcJdbc
Jdbc
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
Drools
DroolsDrools
Drools
 
2001: JNDI Its all in the Context
2001:  JNDI Its all in the Context2001:  JNDI Its all in the Context
2001: JNDI Its all in the Context
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3
 
Struts2 - 101
Struts2 - 101Struts2 - 101
Struts2 - 101
 
Jndi (1)
Jndi (1)Jndi (1)
Jndi (1)
 
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code ExampleMaven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
 

Andere mochten auch

javasebeyondbasics
javasebeyondbasicsjavasebeyondbasics
javasebeyondbasics
webuploader
 
Spring Data and MongoDB
Spring Data and MongoDBSpring Data and MongoDB
Spring Data and MongoDB
Oliver Gierke
 
Spring mvc my Faviourite Slide
Spring mvc my Faviourite SlideSpring mvc my Faviourite Slide
Spring mvc my Faviourite Slide
Daniel Adenew
 

Andere mochten auch (20)

Documentacion De Los Procesos
Documentacion De Los ProcesosDocumentacion De Los Procesos
Documentacion De Los Procesos
 
Metodologia rup
Metodologia rupMetodologia rup
Metodologia rup
 
Modelo Del Negocio con RUP y UML Parte 1
Modelo Del Negocio con RUP y UML Parte 1Modelo Del Negocio con RUP y UML Parte 1
Modelo Del Negocio con RUP y UML Parte 1
 
javasebeyondbasics
javasebeyondbasicsjavasebeyondbasics
javasebeyondbasics
 
Spring Data and MongoDB
Spring Data and MongoDBSpring Data and MongoDB
Spring Data and MongoDB
 
Java annotation
Java annotationJava annotation
Java annotation
 
Java annotations
Java annotationsJava annotations
Java annotations
 
Coding standard
Coding standardCoding standard
Coding standard
 
Spring Framework - Validation
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - Validation
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data Access
 
Galaxy S II: samsung publica una guía para la actualización a Android ICS
Galaxy S II: samsung publica una guía para la actualización a Android ICSGalaxy S II: samsung publica una guía para la actualización a Android ICS
Galaxy S II: samsung publica una guía para la actualización a Android ICS
 
Spring Portlet MVC
Spring Portlet MVCSpring Portlet MVC
Spring Portlet MVC
 
Junit
JunitJunit
Junit
 
Spring Framework - Web Flow
Spring Framework - Web FlowSpring Framework - Web Flow
Spring Framework - Web Flow
 
Java Annotation
Java AnnotationJava Annotation
Java Annotation
 
Spring Framework - Expression Language
Spring Framework - Expression LanguageSpring Framework - Expression Language
Spring Framework - Expression Language
 
Annotations
AnnotationsAnnotations
Annotations
 
Los mejores trucos de Asterisk
Los mejores trucos de AsteriskLos mejores trucos de Asterisk
Los mejores trucos de Asterisk
 
Understanding Annotations in Java
Understanding Annotations in JavaUnderstanding Annotations in Java
Understanding Annotations in Java
 
Spring mvc my Faviourite Slide
Spring mvc my Faviourite SlideSpring mvc my Faviourite Slide
Spring mvc my Faviourite Slide
 

Ähnlich wie Simple Jdbc With Spring 2.5

Distributed Objects: CORBA/Java RMI
Distributed Objects: CORBA/Java RMIDistributed Objects: CORBA/Java RMI
Distributed Objects: CORBA/Java RMI
elliando dias
 
Apache Con Us2007 Apachei Batis
Apache Con Us2007 Apachei BatisApache Con Us2007 Apachei Batis
Apache Con Us2007 Apachei Batis
day
 
Slaven tomac unit testing in angular js
Slaven tomac   unit testing in angular jsSlaven tomac   unit testing in angular js
Slaven tomac unit testing in angular js
Slaven Tomac
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011
Agora Group
 

Ähnlich wie Simple Jdbc With Spring 2.5 (20)

JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
 
Jdbc
JdbcJdbc
Jdbc
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Distributed Objects: CORBA/Java RMI
Distributed Objects: CORBA/Java RMIDistributed Objects: CORBA/Java RMI
Distributed Objects: CORBA/Java RMI
 
10 J D B C
10  J D B C10  J D B C
10 J D B C
 
GlassFish REST Administration Backend at JavaOne India 2012
GlassFish REST Administration Backend at JavaOne India 2012GlassFish REST Administration Backend at JavaOne India 2012
GlassFish REST Administration Backend at JavaOne India 2012
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5
 
Basi Dati F2
Basi Dati F2Basi Dati F2
Basi Dati F2
 
Apache Con Us2007 Apachei Batis
Apache Con Us2007 Apachei BatisApache Con Us2007 Apachei Batis
Apache Con Us2007 Apachei Batis
 
Jdbc tutorial
Jdbc tutorialJdbc tutorial
Jdbc tutorial
 
企业级软件的组件化和动态化开发实践
企业级软件的组件化和动态化开发实践企业级软件的组件化和动态化开发实践
企业级软件的组件化和动态化开发实践
 
Slaven tomac unit testing in angular js
Slaven tomac   unit testing in angular jsSlaven tomac   unit testing in angular js
Slaven tomac unit testing in angular js
 
Module 5 jdbc.ppt
Module 5   jdbc.pptModule 5   jdbc.ppt
Module 5 jdbc.ppt
 
Java beans
Java beansJava beans
Java beans
 
GlassFish REST Administration Backend
GlassFish REST Administration BackendGlassFish REST Administration Backend
GlassFish REST Administration Backend
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011
 
Jdbc
JdbcJdbc
Jdbc
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 

Mehr von David Motta Baldarrago

Mehr von David Motta Baldarrago (11)

Android web services - Spring Android
Android web services - Spring AndroidAndroid web services - Spring Android
Android web services - Spring Android
 
Repositorio SVN Google Code
Repositorio SVN Google CodeRepositorio SVN Google Code
Repositorio SVN Google Code
 
Diseño Agil con TDD
Diseño Agil con TDDDiseño Agil con TDD
Diseño Agil con TDD
 
Lo nuevo en Spring 3.0
Lo nuevo  en Spring 3.0Lo nuevo  en Spring 3.0
Lo nuevo en Spring 3.0
 
Scjp Sun Certified Programmer For Java 6 Exam 310 065
Scjp Sun Certified Programmer For Java 6 Exam 310 065Scjp Sun Certified Programmer For Java 6 Exam 310 065
Scjp Sun Certified Programmer For Java 6 Exam 310 065
 
Modelo Del Negocio con RUP y UML Parte 3
Modelo Del Negocio con RUP y UML Parte 3Modelo Del Negocio con RUP y UML Parte 3
Modelo Del Negocio con RUP y UML Parte 3
 
Modelo Del Negocio con RUP y UML Parte 2
Modelo Del Negocio con RUP y UML Parte 2Modelo Del Negocio con RUP y UML Parte 2
Modelo Del Negocio con RUP y UML Parte 2
 
Upgrade Zaptel to DAHDI
Upgrade Zaptel to DAHDIUpgrade Zaptel to DAHDI
Upgrade Zaptel to DAHDI
 
Instalacion de Elastix
Instalacion de ElastixInstalacion de Elastix
Instalacion de Elastix
 
Elastix Without Tears
Elastix Without TearsElastix Without Tears
Elastix Without Tears
 
Instalacion Debian + Asterisk + FreePbx + A2Billing
Instalacion Debian + Asterisk + FreePbx + A2BillingInstalacion Debian + Asterisk + FreePbx + A2Billing
Instalacion Debian + Asterisk + FreePbx + A2Billing
 

Kürzlich hochgeladen

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

Simple Jdbc With Spring 2.5

  • 1. Simple JDBC with Spring 2.5 Thomas Risberg SpringSource Inc. Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
  • 2. Introduction • Background - COBOL programmer, Oracle DBA, J2EE developer, Spring developer, SpringSource employee • Committer on the Spring Framework project since 2003, supporting the JDBC and Data Access code • Co-author of “Professional Java Development with the Spring Framework” from Wrox Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 2
  • 3. Agenda • JDBC development doesn’t have to be difficult • When is JDBC more appropriate than an ORM solution • Look at new Spring 2.5 JDBC features • A few other 2.5 features that are handy for data access development and testing Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 3
  • 4. Yuck!! public class JdbcDaoImpl { public int getCustomerCount() { Connection conn = null; Statement stmt = null; ResultSet rs = null; int count = 0; Properties properties = new Properties(); try { properties.load(new FileInputStream("jdbc.properties")); Using } catch (IOException e) { throw new MyDataAccessException(“I/O Error”, e); } try { straight Class.forName(properties.getProperty("driverClassName")); conn = DriverManager.getConnection(properties.getProperty("url"), properties); stmt = conn.createStatement(); rs = stmt.executeQuery("select count(*) from customers"); JDBC code if (rs.next()) { count = rs.getInt(1); } } catch (ClassNotFoundException e) { throw new MyDataAccessException(“JDBC Error”, e); } catch (SQLException se) { throw new MyDataAccessException(“JDBC Error”, se); } finally { if (rs != null) { try { rs.close(); } catch (SQLException ignore) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException ignore) {} } if (conn != null) { try { conn.close(); } catch (SQLException ignore) {} } Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. } 4 return count; } }
  • 5. Much better! @Repository public class SpringDaoImpl { private JdbcTemplate jdbcTemplate; @Autowired public void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } public int getCustomerCount() { return jdbcTemplate.queryForInt("select count(*) from customers"); } } <context:property-placeholder location="classpath:jdbc.properties"/> <context:annotation-config/> <context:component-scan base-package="com.springsource.data.sample"/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${db.driverClassName}"/> <property name="url" value="${db.url}"/> <property name="username" value="${db.username}"/> <property name="password" value="${db.password}"/> </bean> Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 5
  • 6. Who does what? Task Spring You Connection Management √ SQL √ Statement Management √ ResultSet Management √ Row Data Retrieval √ Parameter Declaration √ Parameter Setting √ Transaction Management √ Exception Handling √ Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 6
  • 7. Plain JDBC vs. Spring JDBC JDBC Spring DriverManager / DataSource DataSource Statement / JdbcTemplate / PreparedStatement / SimpleJdbcTemplate, CallableStatement SimpleJdbcCall, SimpleJdbcInsert MappingSqlQuery / StoredProcedure ResultSet / RowSet POJOs / List of POJOs or Maps / SqlRowSet Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 7
  • 8. Exception Translation SQLException is translated to a more expressive sub-class of DataAccessException like DataIntegrityViolationException or CannotAcquireLockException. This is translation is based on SQL Error codes forts and then SQL State codes. Translation is controlled by entries in sql-error-codes.xml. sql-error-codes.xml <bean id="MySQL" class="org.springframework.jdbc.support.SQLErrorCodes"> <property name="badSqlGrammarCodes"> <value>1054,1064,1146</value> </property> <property name="dataAccessResourceFailureCodes"> <value>1</value> </property> <property name="dataIntegrityViolationCodes"> <value>1062</value> </property> <property name="cannotAcquireLockCodes"> <value>1205</value> </property> <property name="deadlockLoserCodes"> <value>1213</value> </property> </bean> Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 8
  • 9. Jobs? Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 9
  • 10. When should you use JDBC? • Trivial domain model, few tables • Complex queries reading and modifying multiple tables • Stored procedures, db specific data types • Bulk operations • Tasks where you are not mapping relational data to an object graph Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 10
  • 11. Mix JDBC and ORM • It’s not an either or situation • You can mix ORM access with JDBC • Stored procedures are typically better supported with JDBC • ORM and JDBC share transaction management - can participate in same transaction • Remember to flush ORM session/entity manager before JDBC access Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 11
  • 12. Simple Example • Single Table (MySQL) CREATE TABLE customer ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(50), customer_number varchar(50), birth_date date, PRIMARY KEY USING BTREE (id) ) ENGINE= InnoDB DEFAULT CHARSET= latin1 Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 12
  • 13. The Customer class package com.springsource.data.sample.domain; import java.util.Date; public class Customer { private Long id; private String name; private String customerNumber; private Date birthDate; // getters and setters // } Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 13
  • 14. DAO/Repository Interface package com.springsource.data.sample.repository; import java.util.List; import com.springsource.data.sample.domain.Customer; public interface CustomerRepository { void add(Customer customer); Customer findById(Long id); void save(Customer customer); List<Customer> findAll(); } Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 14
  • 15. Spring 2.5 and SimpleJdbc • Spring 2.5 features for Simple JDBC: – SimpleJdbcTemplate (named parameter support) – SimpleJdbcInsert – SimpleJdbcCall – Annotation configuration • @Repository, @Service, @Component • @Autowired, @Qualifier – JUnit 4 support • @RunWith(SpringJUnit4ClassRunner.class) • @ContextConfiguration • @Transactional @Test Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 15
  • 16. Simple Queries Customer customer = simpleJdbcTemplate.queryForObject( "select id, name, customer_number, birth_date from customer where id = ?", ParameterizedBeanPropertyRowMapper.newInstance(Customer.class), id); List<Customer> customerList = simpleJdbcTemplate.query( "select id, name, customer_number, birth_date from customer", ParameterizedBeanPropertyRowMapper.newInstance(Customer.class)); Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 16
  • 17. Simple Updates named parameters simpleJdbcTemplate.update( "update customer set name = :name, birth_date = :birth_date where id = :id", new BeanPropertySqlParameterSource(customer)); source of values to match parameters Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 17
  • 18. Passing in parameter values • java.util.Map – simple but doesn’t provide type info • MapSqlParameterSource – provides option of passing in SQL type values.addValue("birth_date", customer.getBirthdate(), Types.DATE) • BeanPropertySqlParameterSource – automatic mapping of property values from a JavaBean to parameters of same name – provides option of specifying SQL type values.registerSqlType("birth_date", Types.DATE) Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 18
  • 19. Mapping results • ParameterizedRowMapper – provides for customized mapping from results data to domain class • ParameterizedBeanPropertyRowMapper – automatic mapping from results data to a JavaBean. Column names are mapped to properties. (Use column aliases if names don’t match) Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 19
  • 20. Live Code Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 20
  • 21. Insert data and access generated keys • Traditionally a bit tricky - need to use PreparedStatementCreator and a KeyHolder • What if - – you knew the name of the table – the name and type of the columns • Maybe the JDBC framework could provide the rest ... Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 21
  • 22. Database Metadata customer table column name parameter type Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 22
  • 23. SimpleJdbcInsert private SimpleJdbcInsert insertCustomer; ... this.insertCustomer = new SimpleJdbcInsert(dataSource) .withTableName("customer") .usingGeneratedKeyColumns("id"); Number newId = insertCustomer.executeAndReturnKey( new BeanPropertySqlParameterSource(customer)); customer.setId(newId.longValue()); Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 23
  • 24. SimpleJdbcInsert • Simplifies insert operations • Uses table metadata to provide automatic column configuration • Option to provide explicit configuration • Supports auto generated keys in a database independent fashion • Supports batch inserts of arrays of Maps or SqlParameters Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 24
  • 25. Live Code Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 25
  • 26. Stored Procedures • Are they really that hard to use? • What if - – you knew the name of the procedure – the name and type of the parameters • Maybe the JDBC framework could provide the rest ... Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 26
  • 27. generate_customer_no declaration CREATE PROCEDURE generate_customer_no( IN in_prefix varchar(10), OUT out_customer_no varchar(50)) BEGIN SELECT CONCAT(in_prefix, '.', (RAND() * 10000000)) INTO out_customer_no; END Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 27
  • 28. Database Metadata generate_customer_no in or out procedure name column/parameter name SQL type Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 28
  • 29. SimpleJdbcCall generate_customer_no private SimpleJdbcCall generateCustomerNumberCall; ... this.generateCustomerNumberCall = new SimpleJdbcCall(dataSource) .withProcedureName("generate_customer_no"); String customerNumber = generateCustomerNumberCall.executeObject( String.class, Collections.singletonMap("in_prefix", "XYZ")); Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 29
  • 30. SimpleJdbcCall DEBUG output DEBUG [org.springframework.jdbc.core.simple.SimpleJdbcCall] - JdbcCall call not compiled before execution - invoking compile DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataProviderFactory] - Using org.springframework.jdbc.core.metadata.GenericCallMetaDataProvider DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataProvider] - Retrieving metadata for null/null/generate_customer_no DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataProvider] - Retrieved metadata: in_prefix 1 12 VARCHAR false DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataProvider] - Retrieved metadata: out_customer_no 4 12 VARCHAR false DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataContext] - Added metadata in parameter for: in_prefix DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataContext] - Added metadata out parameter for: out_customer_no DEBUG [org.springframework.jdbc.core.simple.SimpleJdbcCall] - Compiled stored procedure. Call string is [{call generate_customer_no(?, ?)}] DEBUG [org.springframework.jdbc.core.simple.SimpleJdbcCall] - SqlCall for procedure [generate_customer_no] compiled DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataContext] - Matching {in_prefix=XYZ} with {out_customer_no=out_customer_no, in_prefix=in_prefix} DEBUG [org.springframework.jdbc.core.simple.SimpleJdbcCall] - The following parameters are used for call {call generate_customer_no(?, ?)} with: {in_prefix=XYZ} DEBUG [org.springframework.jdbc.core.simple.SimpleJdbcCall] - 1: in_prefix SQL Type 12 Type Name null org.springframework.jdbc.core.SqlParameter DEBUG [org.springframework.jdbc.core.simple.SimpleJdbcCall] - 2: out_customer_no SQL Type 12 Type Name null org.springframework.jdbc.core.SqlOutParameter DEBUG [org.springframework.jdbc.core.JdbcTemplate] - Calling stored procedure [{call generate_customer_no(?, ?)}] DEBUG [org.springframework.jdbc.core.StatementCreatorUtils] - Setting SQL statement parameter value: column index 1, parameter value [XYZ], value class [java.lang.String], SQL type 12 DEBUG [org.springframework.jdbc.core.JdbcTemplate] - CallableStatement.execute() returned 'false' DEBUG [org.springframework.jdbc.core.JdbcTemplate] - CallableStatement.getUpdateCount() returned 0 INFO [org.springframework.jdbc.core.JdbcTemplate] - Added default SqlReturnUpdateCount parameter named #update-count-1 DEBUG [org.springframework.jdbc.core.JdbcTemplate] - CallableStatement.getUpdateCount() returned -1 Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 30
  • 31. SimpleJdbcCall • Simplifies access to stored procedures • Any database can be used with explicit parameter configuration • Supported databases provides automatic parameter configuration: – Apache Derby – DB2 – MySQL – Microsoft SQL Server – Oracle – Sybase Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 31
  • 32. Live Code Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 32
  • 33. Q&A Questions? thomas.risberg@springsource.com Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 33
  • 34. Source Code Customer.java package com.springsource.data.sample.domain; import java.util.Date; public class Customer { private Long id; private String name; private String customerNumber; private Date birthDate; public Long getId() { return id; } public void setId(Long id) { this.id = id; } (continued) Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 34
  • 35. Source Code Customer.java (continued) public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCustomerNumber() { return customerNumber; } public void setCustomerNumber(String customerNumber) { this.customerNumber = customerNumber; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } } Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 35
  • 36. Source Code SimpleCustomerRepository.java package com.springsource.data.sample.repository; import java.util.Collections; import java.util.List; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper; import org.springframework.jdbc.core.simple.SimpleJdbcCall; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; import org.springframework.stereotype.Repository; import com.springsource.data.sample.domain.Customer; @Repository public class SimpleCustomerRepository implements CustomerRepository { private SimpleJdbcTemplate simpleJdbcTemplate; private SimpleJdbcInsert insertCustomer; private SimpleJdbcCall generateCustomerNumberCall; (continued) Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 36
  • 37. Source Code SimpleCustomerRepository.java (continued) @Autowired public void init(DataSource dataSource) { this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); this.insertCustomer = new SimpleJdbcInsert(dataSource) .withTableName("customer") .usingGeneratedKeyColumns("id"); this.generateCustomerNumberCall = new SimpleJdbcCall(dataSource) .withProcedureName("generate_customer_no"); } public void add(Customer customer) { String customerNumber = generateCustomerNumberCall.executeObject( String.class, Collections.singletonMap("in_prefix", "XYZ")); customer.setCustomerNumber(customerNumber); Number newId = insertCustomer.executeAndReturnKey( new BeanPropertySqlParameterSource(customer)); customer.setId(newId.longValue()); } (continued) Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 37
  • 38. Source Code SimpleCustomerRepository.java (continued) public Customer findById(Long id) { Customer customer = simpleJdbcTemplate.queryForObject( "select id, name, customer_number, birth_date from customer where id = ?", ParameterizedBeanPropertyRowMapper.newInstance(Customer.class), id); return customer; } public void save(Customer customer) { simpleJdbcTemplate.update( "update customer set name = :name, birth_date = :birthDate where id = :id", new BeanPropertySqlParameterSource(customer)); } public List<Customer> findAll() { List<Customer> customerList = simpleJdbcTemplate.query( "select id, name, customer_number, birth_date from customer", ParameterizedBeanPropertyRowMapper.newInstance(Customer.class)); return customerList; } } Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 38
  • 39. Source Code CustomerRepository4Tests.java package com.springsource.data.sample.repository; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Date; import java.util.List; import javax.sql.DataSource; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import com.springsource.data.sample.domain.Customer; (continued) Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 39
  • 40. Source Code CustomerRepository4Tests.java (continued) @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class CustomerRepository4Tests { @Autowired private CustomerRepository customerRepository; @Autowired private DataSource dataSource; @Before public void onSetUpInTransaction() throws Exception { // Load test data JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.execute("delete from customer"); jdbcTemplate.execute( "insert into customer (id, customer_number, name, birth_date) " + "values (1, 'Z.12345.67890', 'Bubba', '1990-02-03')"); jdbcTemplate.execute( "insert into customer (id, customer_number, name, birth_date) " + "values (2, 'Z.12345.98765', 'Mary', '1988-01-31')"); } (continued) Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 40
  • 41. Source Code CustomerRepository4Tests.java (continued) @Transactional @Test public void testFindAll() { List<Customer> l = customerRepository.findAll(); assertEquals("Wrong number of customers returned", 2, l.size()); } @Transactional @Test public void testFindById() { Customer c = customerRepository.findById(2L); assertNotNull("Customer not found", c); } @Transactional @Test public void testAddCustomer() { Customer c = new Customer(); c.setBirthDate(new Date(19829922L)); c.setName("Sven"); customerRepository.add(c); assertNotNull("Customer id not assigned", c.getId()); assertTrue("Bad customer id", 3 <= c.getId()); assertNotNull("Customer number not assigned", c.getCustomerNumber()); } (continued) Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 41
  • 42. Source Code CustomerRepository4Tests.java (continued) @Transactional @Test public void testUpdateCustomer() { Customer c = customerRepository.findById(2L); c.setBirthDate(new Date(19829933L)); customerRepository.save(c); Customer c2 = customerRepository.findById(2L); assertEquals("BirthDate not updated", 18000000L, c2.getBirthDate().getTime()); } } Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 42
  • 43. Source Code CustomerRepository4Tests-context.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:annotation-config/> <context:component-scan base-package="com.springsource.data.sample"/> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}"/> <tx:annotation-driven/> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource"/> </beans> Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 43