Query
@GetMapping("/students")
public List<Student> select() {
String sql = "SELECT id, name FROM student";
Map<String, Object> map = new HashMap<>();
//可以用lambda表達式傳入rowmapper
/*List<Student> studentList = namedParameterJdbcTemplate.query(sql, map, (rs,rowNum) ->
new Student(rs.getInt("id"),rs.getString("name")) );*/ //也可以另外單獨寫一個RowMapper 要繼承RowMapper接口
List<Student> studentList = namedParameterJdbcTemplate.query(sql, map, new StudentRowMapper());
return studentList;
}
@GetMapping("/students/{studentId}")
public Student select(@PathVariable Integer studentId) {
String sql = "SELECT id, name FROM student WHERE id= :studentId";
Map<String, Object> map = new HashMap<>();
map.put("studentId", studentId);
List<Student> students = namedParameterJdbcTemplate.query(sql, map,new StudentRowMapper());
return students.isEmpty() ? null : students.get(0);
}
- Rowmapper同時也可以替換成ResultSetExtractor
- RowMapper一次是一行行讀取
- ResultSetExtractor是一次性的把所有數據讀出來
- 小資料集影響不大,大資料集ResultSetExtractor就會有性能疑慮
//用resultSetExtractor改寫
List<Student> students = namedParameterJdbcTemplate.query(sql, map, new ResultSetExtractor<List<Student>>() {
@Override
public List<Student> extractData(ResultSet rs) throws SQLException, DataAccessException
{
List<Student> result = new ArrayList<>();
while (rs.next())
{
Student s = new Student(rs.getInt("id"), rs.getString("name"));
result.add(s);
} return result;
}
});
return students.isEmpty() ? null : students.get(0);