JdbcTemplate queryForStream Example Spring 5.3

Published
Updated

DataClassRowMapper Example

The following example uses Spring 5.3’s new DataClassRowMapper which can automatically instantiate a new instance of the specified target class.

@Autowired
JdbcTemplate jdbcTemplate;

private String SQL_QUERY = "SELECT make, model FROM vehicles";

// Example using DataClassRowMapper
Stream<Vehicle> stream = jdbcTemplate.queryForStream(
        SQL_QUERY,
        new DataClassRowMapper<Vehicle>());

RowMapper Lambda Example

The following example uses Java’s lambda implementation of the RowMapper to map the resultSet to a target constructor.

@Autowired
JdbcTemplate jdbcTemplate;

private String SQL_QUERY = "SELECT make, model FROM vehicles";

// Example using RowMapper Lambda
Stream<Vehicle> stream = jdbcTemplate.queryForStream(
        SQL_QUERY,
        (rs, rowNum) -> new Vehicle(
            rs.getString("make"),
            rs.getString("model")));

Example of QueryForStream using a Prepared Statement

The following is an example of how to use the DataClassRowMapper with a prepared statement using a jdbcTemplate.

@Autowired
JdbcTemplate jdbcTemplate;

// Example using a Prepared Statement
Stream<Vehicle> stream = jdbcTemplate.queryForStream(
        "SELECT make, model FROM vehicles WHERE make = ?",
        new DataClassRowMapper<Vehicle>(),
        "FORD");

Full source code of examples

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.DataClassRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.stream.Stream;

public class JdbcTemplateStreamExample {

    @Autowired
    JdbcTemplate jdbcTemplate;

    private String SQL_QUERY = "SELECT make, model FROM vehicles";

    public void example() {
        // Example using DataClassRowMapper
        Stream<Vehicle> streamA = jdbcTemplate.queryForStream(
                SQL_QUERY,
                new DataClassRowMapper<Vehicle>());

        // Example using RowMapper Lambda
        Stream<Vehicle> streamB = jdbcTemplate.queryForStream(
                SQL_QUERY,
                (rs, rowNum) -> new Vehicle(
                    rs.getString("make"),
                    rs.getString("model")
                ));

        // Example using a Prepared Statement
        Stream<Vehicle> streamC = jdbcTemplate.queryForStream(
                "SELECT make, model FROM vehicles WHERE make = ?",
                new DataClassRowMapper<Vehicle>(),
                "FORD");
    }

    static protected class Vehicle {

        private String make;
        private String model;

        public Vehicle(String make, String model) {
            this.make = make;
            this.model = model;
        }
    }
}