網頁

2020/4/1

Spring JDBC MapSqlParameterSource

當使用Spring JDBC的NamedParameterJdbcTemplate執行SQL操作時,其提供的方法除了可用Map<String, ?>帶入參數,也可改用SqlParameterSource的實作類別MapSqlParameterSource

MapSqlParameterSource其實只是對LinkedHasdMap<String, Object>做包裝來提供fluent風格的方式來傳入參數。節錄原始碼如下。

MapSqlParameterSource

public class MapSqlParameterSource extends AbstractSqlParameterSource {

    private final Map<String, Object> values = new LinkedHashMap<>();
    ...
   
    public MapSqlParameterSource addValue(String paramName, @Nullable Object value) {
        Assert.notNull(paramName, "Parameter name must not be null");
        this.values.put(paramName, value);
        if (value instanceof SqlParameterValue) {
            registerSqlType(paramName, ((SqlParameterValue) value).getSqlType());
        }
        return this;
    }
    ...
}

使用範例如下。

DemoDao

package com.abc.demo.dao;

import com.abc.demo.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DemoDao {

    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    // 使用NamedParameterJdbcTemplate
    public List<Employee> getEmployeeByAgeGreaterThanAndTitle(Integer age, String title) {
        String sql = "SELECT * FROM EMPLOYEE WHERE AGE >= :age AND TITLE = :title";

        MapSqlParameterSource params = new MapSqlParameterSource()
                        .addValue("age", age)
                        .addValue("title", title);

        List<Employee> employeeList =
                namedParameterJdbcTemplate.query(sql, params, (rs, rowNum) -> {
                    Employee employee = new Employee();
                    employee.setId(rs.getLong("ID"));
                    employee.setName(rs.getString("NAME"));
                    employee.setAge(rs.getInt("AGE"));
                    employee.setTitle(rs.getString("TITLE"));
                    return employee;
                });

        return employeeList;
    }
    
}

參考:

沒有留言:

張貼留言