0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【SpringBoot】NamedParameterJdbcTemplateで実行されるSQL文をログ出力する

Posted at

備考(※読み飛ばし推奨)

  • 業務で役立ったので備忘録として残すことにした。
  • log4jdbcで実装すべきだが、Gradle(Maven)を書き換えるのが面倒な人向け。
  • NamedParameterではないJdbcTemplate使用時はString.replaceFirst?を置換すればいけそうな気がするが、パラメータの順番担保はどうなるのか未確認。log4jdbcを使うべき。

サンプルコード

package sample.repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Map;

@Repository
public class SampleRepositoryImpl implements SampleRepository {

    @Autowired
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Override
    public void update(String sql, MapSqlParameterSource params) 
    {
        // SQL実行直前にログに吐き出す。
        sqlPrint(sql,params);
        namedParameterJdbcTemplate.update(sql, params);
    }

    /**
     * SQL文を標準出力する
     * @param sql SQLクエリ文字列
     * @param params パラメータ
     */
    private void sqlPrint(String sql, MapSqlParameterSource params)
    {
        Map<String, Object> param = params.getValues();
        for(String key : param.keySet())
        {
            result = result.replaceAll(":" + key, "'" + param.get(key).toString() + "'");
        }
        System.out.println(result);
    }
}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?