Close

Spring - JdbcTemplate Example

[Last Updated: Feb 24, 2017]

Spring JdbcTemplate implements the interface JdbcOperations. Spring template classes are based on Template method pattern.

Most of the common repetitive logic, like opening the database connection, preparing the Jdbc statements, handling and processing exception, handling transactions, closing the connection are done by JdbcTemplate object for us. During this process, JdbcTemplate calls the client code asking for application specific things like the sql statement along with parameters and for processing the result set (typically a call back on RowMapper).

For a concise description of the methods in this class and to have a good understanding of them, please check out our last tutorial.

Example

Following example demonstrate all CRUD operations using JdbcTemplate. We also used DAO pattern to keep client code independent of database queries.


Example Project

Dependencies and Technologies Used:

  • Spring Context 4.2.3.RELEASE: Spring Context.
  • Spring JDBC 4.2.3.RELEASE: Spring JDBC.
  • H2 Database Engine 1.4.190: H2 Database Engine.
  • JDK 1.8
  • Maven 3.0.4

Spring Jdbc Template Example Select All Download
  • spring-jdbc-template
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • JdbcTemplatePersonDao.java
          • resources

    We used embedded H2 database in above example. By default H2 uses in memory database. Spring has native support (org.springframework.jdbc.datasource.embedded) for embedded Java databases e.g. HSQL, H2, and Derby.

    In our pom.xml, we also added a new spring dependency: spring-jdbc.


    Here's the output logs:

    Jan 05, 2016 4:40:45 AM com.logicbig.example.AppController process
    INFO: person count 2
    Jan 05, 2016 4:40:45 AM com.logicbig.example.AppController process
    INFO: persons found by last name [Person{id=1, firstName='Dana', lastName='Whitley',
        address='464 Gorsuch Drive'}]
    Jan 05, 2016 4:40:45 AM com.logicbig.example.AppController process
    INFO: found person by id : Person{id=2, firstName='Robin', lastName='Cash', address='64 Zella Park'}
    Jan 05, 2016 4:40:45 AM com.logicbig.example.AppController process
    INFO: All persons : [Person{id=1, firstName='Dana', lastName='Whitley', address='464 Gorsuch Drive'},
        Person{id=2, firstName='Robin', lastName='Cash', address='64 Zella Park'}]
    Jan 05, 2016 4:40:45 AM com.logicbig.example.AppController process
    INFO: Address updated Person{id=1, firstName='Dana', lastName='Whitley', address='Jweitt Circle'}
    Jan 05, 2016 4:40:45 AM com.logicbig.example.AppController process
    INFO: All persons : [Person{id=1, firstName='Dana', lastName='Whitley', address='Jweitt Circle'}]
    

    See Also