Spring - NamedParameterJdbcTemplate

Last Updated : 4 May, 2026

NamedParameterJdbcTemplate is a class in the Spring JDBC framework that enhances database access by allowing the use of named parameters instead of traditional ? placeholders. It works as a wrapper around JdbcTemplate and internally delegates execution to it.

  • Allows use of named parameters (e.g., :id, :name) instead of positional parameters.
  • Supports passing parameters using Map or SqlParameterSource for flexibility.
  • Improves readability and reduces errors caused by incorrect parameter ordering.

Syntax of execute()

public <T> T execute(String sql, SqlParameterSource paramSource, PreparedStatementCallback<T> action)

  • sql: SQL query with named parameters (e.g., :id, :name)
  • paramSource: SqlParameterSource implementation (like MapSqlParameterSource) for binding parameters
  • paramMap: Map-based parameter binding (simpler alternative)
  • action: Callback interface used to execute operations on PreparedStatement

Step-by-Step Implementation

This section demonstrates how to configure, implement, and run a Spring application using NamedParameterJdbcTemplate to perform database operations in a structured manner.

Step 1: Create Database Table

  • Create a table to store student data.
  • Ensure id is the primary key.

CREATE TABLE STUDENT (

id INT PRIMARY KEY,

name VARCHAR(45),

department VARCHAR(45)

);

Step 2: Add Maven Dependencies

  • Add Spring JDBC and Context for database operations.
  • Add MySQL driver for database connectivity.
XML
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.23</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.23</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.28</version>
    </dependency>
</dependencies>

Step 3: Configure Spring Beans (AppConfig.java)

  • Configure DataSource to connect to the database.
  • Define NamedParameterJdbcTemplate bean.
Java
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/school_db");
        ds.setUsername("dbuser");
        ds.setPassword("securepassword");
        return ds;
    }

    @Bean
    public NamedParameterJdbcTemplate namedParameterJdbcTemplate() {
        return new NamedParameterJdbcTemplate(dataSource());
    }
}

Step 4: Create Model Class (Student.java)

  • Represents the STUDENT table.
  • Contains fields, constructor, and getters/setters.
Java
public class Student {
    private int id;
    private String name;
    private String department;

    public Student(int id, String name, String department) {
        this.id = id;
        this.name = name;
        this.department = department;
    }

    // getters and setters
}

Step 5: Create DAO Class (StudentDao.java)

  • Handles database operations.
  • Uses named parameters for SQL queries.
Java
@Repository
public class StudentDao {

    private final NamedParameterJdbcTemplate jdbcTemplate;

    @Autowired
    public StudentDao(NamedParameterJdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public void insertStudent(Student student) {
        String sql = "INSERT INTO STUDENT (id, name, department) VALUES (:id, :name, :dept)";

        MapSqlParameterSource params = new MapSqlParameterSource()
                .addValue("id", student.getId())
                .addValue("name", student.getName())
                .addValue("dept", student.getDepartment());

        jdbcTemplate.update(sql, params);
    }

    public Optional<Student> findById(int id) {
        String sql = "SELECT * FROM STUDENT WHERE id = :id";

        try {
            Student student = jdbcTemplate.queryForObject(
                    sql,
                    Collections.singletonMap("id", id),
                    (rs, rowNum) -> new Student(
                            rs.getInt("id"),
                            rs.getString("name"),
                            rs.getString("department"))
            );
            return Optional.of(student);
        } catch (EmptyResultDataAccessException e) {
            return Optional.empty();
        }
    }
}



Step 6: Run the Application

  • Load Spring context.
  • Insert and fetch student data.
Java
public class StudentApplication {
    public static void main(String[] args) {

        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(AppConfig.class);

        StudentDao dao = context.getBean(StudentDao.class);

        Student student = new Student(1, "Geek", "Computer Science");
        dao.insertStudent(student);

        dao.findById(1).ifPresent(System.out::println);

        context.close();
    }
}

Output:

Output
Outputc

Student [id=1, name=Geek, department=Computer Science]

Benefits of NamedParameterJdbcTemplate over JdbcTemplate

  • Uses named parameters instead of ? placeholders.
  • Queries are easier to read and maintain.
  • Reduces errors in complex SQL queries.
  • Simplifies parameter mapping and improves code clarity.
Comment

Explore