在Spring Boot使用JdbcTemplate
在console印出執行的SQL及條件參數的方法如下。
在專案的application.properties
加入logging.level.org.springframework.jdbc.core=TRACE
即可。
application.properties
logging.level.org.springframework.jdbc.core=TRACE
例如在EmployeeDao
中使用NamedParameterJdbcTemplate
執行SQL。
EmployeeDao
package com.abc.demo.dao;
import com.abc.demo.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
@Service
public class EmployeeDao {
@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public Employee findById(long id) {
String sql = "select * from EMPLOYEE where id = :id";
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("id", id);
return namedParameterJdbcTemplate.queryForObject(sql, params, new BeanPropertyRowMapper<>(Employee.class));
}
// by 肉豬
}
執行時會在console印出執行SQL及參數的內容
2020-12-31 14:02:18.612 DEBUG 5448 --- [ main] o.s.j.c.JdbcTemplate : Executing prepared SQL query
2020-12-31 14:02:18.613 DEBUG 5448 --- [ main] o.s.j.c.JdbcTemplate : Executing prepared SQL statement [select * from EMPLOYEE where id = ?]
2020-12-31 14:02:18.617 TRACE 5448 --- [ main] o.s.j.c.StatementCreatorUtils : Setting SQL statement parameter value: column index 1, parameter value [1], value class [java.lang.Long], SQL type unknown
2020-12-31 14:02:18.621 DEBUG 5448 --- [ main] o.s.j.c.BeanPropertyRowMapper : Mapping column 'ID' to property 'id' of type 'java.lang.Long'
2020-12-31 14:02:18.621 DEBUG 5448 --- [ main] o.s.j.c.BeanPropertyRowMapper : Mapping column 'AGE' to property 'age' of type 'java.lang.Integer'
2020-12-31 14:02:18.621 DEBUG 5448 --- [ main] o.s.j.c.BeanPropertyRowMapper : Mapping column 'NAME' to property 'name' of type 'java.lang.String'
沒有留言:
張貼留言