LoginSignup
3
2

More than 3 years have passed since last update.

【SprintBoot】org.springframework.jdbc.core.namedparamに定義された3種類のSqlParameterSourceの使い方

Last updated at Posted at 2019-08-09

SimpleJdbcInsertNamedParameterJdbcTemplateなどにパラメータを渡す際に用いるSqlParameterSourceですが、このインターフェースと同じパッケージ(org.springframework.jdbc.core.namedparam)には以下3種類の実装クラスが存在しています。

  1. MapSqlParameterSource
  2. BeanPropertySqlParameterSource
  3. EmptySqlParameterSource

この記事ではこの3種類のSqlParameterSourceの使い方について書きます。

MapSqlParameterSource

マップ形式でパラメータを登録していくSqlParameterSourceです。
一番汎用的なものですが、場合によっては後述するBeanPropertySqlParameterSourceを使った方が省力化できます。

自分は主に引数をマップしていくような場面で使っています。

クエリ文字列
SELECT *
FROM hoge_table
WHERE hoge_id = :hogeId
  AND hoge_status = :hogeStatus;
クエリ実行(HogeDtoの単体取得処理)
// 初期化は省略
String queryString;
NamedParameterJdbcTemplate jdbc;
BeanPropertyRowMapper<HogeDto> rowMapper;

public HogeDto selectHoge(Integer hogeId, String hogeStatus) {
  MapSqlParameterSource param = new MapSqlParameterSource("hogeId", hogeId)
      .addValue("hogeStatus", hogeStatus);

  return jdbc.queryForObject(queryString, param, rowMapper);
}

BeanPropertySqlParameterSource

オブジェクトを入れるとパラメータとしてよしなに扱ってくれるSqlParameterSourceです。

自分は主にオブジェクトのフィールドの殆どでプリペアドステートメントを埋めたり、SimpleJdbcInsertを使うような場合に使います。

クエリ文字列
UPDATE hoge_sub_value
SET hoge_value = :hogeValue
WHERE hoge_id = :hogeId
  AND hoge_status = :hogeStatus
クエリ実行(hoge_sub_valueの複数更新)
// 初期化は省略
String queryString;
NamedParameterJdbcTemplate jdbc;

public void updateHogeSubValues(List<HogeSubValue> subValues) {
  BeanPropertySqlParameterSource[] params = subValues.stream()
      .map(BeanPropertySqlParameterSource::new)
      .toArray(SqlParameterSource[]::new);

  jdbc.batchUpdate(queryString, params);
}

EmptySqlParameterSource

最後は、パラメータを使わないことを示すEmptySqlParameterSourceです。

NamedParameterJdbcTemplateにはSqlParameterSourceの有無で別々のインターフェースが定義されていますが(e.g. <T> T query(String sql, SqlParameterSource paramSource, ResultSetExtractor<T> rse)<T> T query(String sql, ResultSetExtractor<T> rse))、以下の通り、内部的にはパラメータ有りの実装にEmptySqlParameterSourceを渡すという形で実装されています。

使う場面はあまり無いと思います。

NamedParameterJdbcTemplate.java(167〜187行目辺り)の実装
@Override
@Nullable
public <T> T query(
    String sql, SqlParameterSource paramSource, ResultSetExtractor<T> rse
) throws DataAccessException {
    return getJdbcOperations().query(getPreparedStatementCreator(sql, paramSource), rse);
}

@Override
@Nullable
public <T> T query(
    String sql, ResultSetExtractor<T> rse
) throws DataAccessException {
    return query(sql, EmptySqlParameterSource.INSTANCE, rse);
}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2