Spring Framework Tutorial

Software Setup and Configuration (STS/Eclipse/IntelliJ)

Core Spring

Spring Annotations

Spring Data

Spring JDBC

Spring Security

Spring - SimpleJDBCTemplate with Example

As of Spring 3.1, SimpleJdbcTemplate was deprecated in favor of the JdbcTemplate. However, for historical context, I will provide an overview of SimpleJdbcTemplate followed by a demonstration using JdbcTemplate, which is the current best practice.

Overview of SimpleJdbcTemplate:

SimpleJdbcTemplate was an enhancement of JdbcTemplate designed to take advantage of Java 5 features like generics. It simplified some database operations but was eventually merged back into the primary JdbcTemplate.

Example using JdbcTemplate:

For this example, let's consider a Student table and perform a basic SELECT operation using JdbcTemplate.

  1. Java Classes:

    Define the Student model:

    public class Student {
        private int id;
        private String name;
        private int age;
    
        // Constructors, getters, setters, and other methods...
    }
    

    A StudentDAO to perform database operations:

    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.jdbc.core.RowMapper;
    
    public class StudentDAO {
        private JdbcTemplate jdbcTemplate;
    
        public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
            this.jdbcTemplate = jdbcTemplate;
        }
    
        public Student getStudent(int id) {
            String query = "SELECT * FROM Student WHERE id = ?";
            return jdbcTemplate.queryForObject(query, new Object[] { id }, new RowMapper<Student>() {
                public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
                    Student student = new Student();
                    student.setId(rs.getInt("id"));
                    student.setName(rs.getString("name"));
                    student.setAge(rs.getInt("age"));
                    return student;
                }
            });
        }
    }
    
  2. Spring Configuration:

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/mydb" />
        <property name="username" value="root" />
        <property name="password" value="password" />
    </bean>
    
    <bean id="studentDAO" class="StudentDAO">
        <property name="jdbcTemplate" ref="jdbcTemplate" />
    </bean>
    
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg ref="dataSource" />
    </bean>
    
  3. Testing:

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class App {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            StudentDAO studentDAO = (StudentDAO) context.getBean("studentDAO");
    
            Student student = studentDAO.getStudent(1);
            System.out.println("Student Details: " + student);
        }
    }
    

When you run the App class, it should fetch the details of the student with ID 1 from the database and print them.

Please note: This example assumes you have the necessary JDBC driver (in this case, MySQL) and DBCP libraries in your classpath. Adjust the configuration accordingly based on your database setup.

  1. SimpleJDBCTemplate in Spring example:

    • Description: Introduces the usage of SimpleJDBCTemplate in the Spring framework for simplified JDBC operations.
    • Code:
      public class JdbcDao {
          private SimpleJdbcTemplate simpleJdbcTemplate;
      
          // Constructor with DataSource injection
          public JdbcDao(DataSource dataSource) {
              this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
          }
      
          // Other methods for JDBC operations using SimpleJDBCTemplate
      }
      
  2. Using SimpleJDBCTemplate for JDBC operations in Spring:

    • Description: Demonstrates how to perform basic JDBC operations using SimpleJDBCTemplate in a Spring application.
    • Code:
      public class JdbcDao {
          private SimpleJdbcTemplate simpleJdbcTemplate;
      
          // Constructor with DataSource injection
          public JdbcDao(DataSource dataSource) {
              this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
          }
      
          // Methods for JDBC operations (query, update, etc.)
      }
      
  3. Spring SimpleJDBCTemplate CRUD operations example:

    • Description: Shows the implementation of Create, Read, Update, and Delete (CRUD) operations using SimpleJDBCTemplate in Spring.
    • Code:
      public class JdbcDao {
          private SimpleJdbcTemplate simpleJdbcTemplate;
      
          // Constructor with DataSource injection
          public JdbcDao(DataSource dataSource) {
              this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
          }
      
          // CRUD operations using SimpleJDBCTemplate
      }
      
  4. Configuring DataSource for SimpleJDBCTemplate in Spring:

    • Description: Guides on configuring a DataSource for SimpleJDBCTemplate in a Spring application.
    • Code:
      @Configuration
      public class AppConfig {
          @Bean
          public DataSource dataSource() {
              // Configure and return DataSource
          }
      
          @Bean
          public JdbcDao jdbcDao(DataSource dataSource) {
              return new JdbcDao(dataSource);
          }
      }
      
  5. SimpleJDBCTemplate queryForObject example:

    • Description: Illustrates the usage of SimpleJDBCTemplate's queryForObject method in Spring.
    • Code:
      public class JdbcDao {
          private SimpleJdbcTemplate simpleJdbcTemplate;
      
          // Constructor with DataSource injection
          public JdbcDao(DataSource dataSource) {
              this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
          }
      
          public String findUsernameById(int userId) {
              String sql = "SELECT username FROM users WHERE id = ?";
              return simpleJdbcTemplate.queryForObject(sql, String.class, userId);
          }
      }
      
  6. Batch processing with SimpleJDBCTemplate in Spring:

    • Description: Demonstrates how to perform batch processing using SimpleJDBCTemplate in a Spring application.
    • Code:
      public class JdbcDao {
          private SimpleJdbcTemplate simpleJdbcTemplate;
      
          // Constructor with DataSource injection
          public JdbcDao(DataSource dataSource) {
              this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
          }
      
          public void batchInsert(List<User> users) {
              String sql = "INSERT INTO users (id, username, email) VALUES (?, ?, ?)";
              List<Object[]> batchArgs = // Create a list of Object arrays
              simpleJdbcTemplate.batchUpdate(sql, batchArgs);
          }
      }
      
  7. Spring SimpleJDBCTemplate named parameters example:

    • Description: Shows how to use named parameters with SimpleJDBCTemplate in Spring.
    • Code:
      public class JdbcDao {
          private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
      
          // Constructor with DataSource injection
          public JdbcDao(DataSource dataSource) {
              this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
          }
      
          public String findUsernameById(int userId) {
              String sql = "SELECT username FROM users WHERE id = :userId";
              Map<String, Object> params = Collections.singletonMap("userId", userId);
              return namedParameterJdbcTemplate.queryForObject(sql, params, String.class);
          }
      }
      
  8. Transaction management with SimpleJDBCTemplate in Spring:

    • Description: Guides on managing transactions using SimpleJDBCTemplate in a Spring application.
    • Code:
      @Service
      @Transactional
      public class JdbcService {
          private SimpleJdbcTemplate simpleJdbcTemplate;
      
          // Constructor with DataSource injection
          public JdbcService(DataSource dataSource) {
              this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
          }
      
          @Transactional
          public void updateUserData(User user) {
              // Perform update operations
          }
      }
      
  9. RowMapper with SimpleJDBCTemplate in Spring:

    • Description: Illustrates how to use a RowMapper with SimpleJDBCTemplate in Spring to map database rows to Java objects.
    • Code:
      public class JdbcDao {
          private SimpleJdbcTemplate simpleJdbcTemplate;
      
          // Constructor with DataSource injection
          public JdbcDao(DataSource dataSource) {
              this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
          }
      
          public List<User> getAllUsers() {
              String sql = "SELECT * FROM users";
              return simpleJdbcTemplate.query(sql, new UserRowMapper());
          }
      
          private static class UserRowMapper implements RowMapper<User> {
              @Override
              public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                  // Map ResultSet to User object
              }
          }
      }
      
  10. SimpleJDBCTemplate update example:

    • Description: Demonstrates how to perform update operations using SimpleJDBCTemplate in Spring.
    • Code:
      public class JdbcDao {
          private SimpleJdbcTemplate simpleJdbcTemplate;
      
          // Constructor with DataSource injection
          public JdbcDao(DataSource dataSource) {
              this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
          }
      
          public void updateUser(User user) {
              String sql = "UPDATE users SET username = ?, email = ? WHERE id = ?";
              simpleJdbcTemplate.update(sql, user.getUsername(), user.getEmail(), user.getId());
          }
      }
      
  11. Pagination with SimpleJDBCTemplate in Spring:

    • Description: Guides on implementing pagination using SimpleJDBCTemplate in a Spring application.
    • Code:
      public class JdbcDao {
          private SimpleJdbcTemplate simpleJdbcTemplate;
      
          // Constructor with DataSource injection
          public JdbcDao(DataSource dataSource) {
              this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
          }
      
          public List<User> getUsersByPage(int offset, int limit) {
              String sql = "SELECT * FROM users LIMIT ? OFFSET ?";
              return simpleJdbcTemplate.query(sql, new UserRowMapper(), limit, offset);
          }
      }
      
  12. Using NamedParameterJdbcTemplate vs SimpleJDBCTemplate in Spring:

    • Description: Compares the usage of NamedParameterJdbcTemplate and SimpleJDBCTemplate in a Spring application.
    • Code:
      public class JdbcDao {
          private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
          private SimpleJdbcTemplate simpleJdbcTemplate;
      
          // Constructors with DataSource injection for both templates
          public JdbcDao(DataSource dataSource) {
              this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
              this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
          }
      
          // Methods using both templates
      }
      
  13. Working with stored procedures using SimpleJDBCTemplate:

    • Description: Demonstrates how to work with stored procedures using SimpleJDBCTemplate in a Spring application.
    • Code:
      public class JdbcDao {
          private SimpleJdbcTemplate simpleJdbcTemplate;
      
          // Constructor with DataSource injection
          public JdbcDao(DataSource dataSource) {
              this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
          }
      
          public void callStoredProcedure(String parameter) {
              String sql = "CALL my_stored_procedure(?)";
              simpleJdbcTemplate.update(sql, parameter);
          }
      }
      
  14. Exception handling in SimpleJDBCTemplate operations in Spring:

    • Description: Guides on handling exceptions in SimpleJDBCTemplate operations in a Spring application.
    • Code:
      public class JdbcDao {
          private SimpleJdbcTemplate simpleJdbcTemplate;
      
          // Constructor with DataSource injection
          public JdbcDao(DataSource dataSource) {
              this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
          }
      
          public void performJdbcOperation() {
              try {
                  // Perform JDBC operation
              } catch (DataAccessException e) {
                  // Handle exceptions
              }
          }
      }
      
  15. SimpleJDBCTemplate batch update example:

    • Description: Shows how to perform batch updates using SimpleJDBCTemplate in Spring.
    • Code:
      public class JdbcDao {
          private SimpleJdbcTemplate simpleJdbcTemplate;
      
          // Constructor with DataSource injection
          public JdbcDao(DataSource dataSource) {
              this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
          }
      
          public void batchUpdate(List<User> users) {
              String sql = "UPDATE users SET status = ? WHERE id = ?";
              List<Object[]> batchArgs = // Create a list of Object arrays
              simpleJdbcTemplate.batchUpdate(sql, batchArgs);
          }
      }
      
  16. Customizing SimpleJDBCTemplate configuration in Spring:

    • Description: Guides on customizing SimpleJDBCTemplate configuration in a Spring application.
    • Code:
      @Configuration
      public class AppConfig {
          @Bean
          public SimpleJdbcTemplate simpleJdbcTemplate(DataSource dataSource) {
              return new SimpleJdbcTemplate(dataSource);
          }
      }
      
  17. Using SimpleJDBCTemplate with Spring Boot:

    • Description: Demonstrates how to use SimpleJDBCTemplate with a Spring Boot application.
    • Code:
      @Service
      public class JdbcService {
          private SimpleJdbcTemplate simpleJdbcTemplate;
      
          // Constructor with DataSource injection
          public JdbcService(DataSource dataSource) {
              this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
          }
      
          // Methods using SimpleJDBCTemplate
      }
      
  18. Handling result sets with SimpleJDBCTemplate in Spring:

    • Description: Shows how to handle result sets using SimpleJDBCTemplate in a Spring application.
    • Code:
      public class JdbcDao {
          private SimpleJdbcTemplate simpleJdbcTemplate;
      
          // Constructor with DataSource injection
          public JdbcDao(DataSource dataSource) {
              this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
          }
      
          public List<String> getUsernames() {
              String sql = "SELECT username FROM users";
              return simpleJdbcTemplate.queryForList(sql, String.class);
          }
      }