SpringBoot中ResultSetExtractor实现编译失败,求正确语法
问题分析与修正方案
原代码的核心问题
- 方法职责混淆:
setTemplate本是注入JdbcTemplate的Setter方法,却被硬塞了查询逻辑,返回类型错误(应为void而非List<Contato>) - 结果集处理遗漏:创建
Contato实例后未添加到列表,最终返回空列表 - 列索引错误:
email、telefone错误使用索引2,需对应各自的数据库列位置 - 冗余代码:
List<Contato> getAllContatoes;未被使用,可直接删除 - API误用:
rs.getNString()不适用于常规字符串列,改用rs.getString()即可
修正后的完整代码
import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.ResultSetExtractor; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class ContatoDao { private JdbcTemplate template; // 标准Setter:仅负责注入JdbcTemplate public void setTemplate(JdbcTemplate template) { this.template = template; } // 独立的查询方法:专门处理联系人列表查询 public List<Contato> getAllContatos() { return template.query("select * from CONTATO", new ResultSetExtractor<List<Contato>>() { @Override public List<Contato> extractData(ResultSet rs) throws SQLException, DataAccessException { List<Contato> list = new ArrayList<>(); while (rs.next()) { Contato e = new Contato(); e.setId(rs.getLong(1)); e.setNome(rs.getString(2)); e.setEmail(rs.getString(3)); // 修正列索引 e.setTelefone(rs.getString(4)); // 修正列索引并改用getString list.add(e); // 将实例添加到列表 } return list; } }); } }
优化建议
- 优先使用列名而非索引(如
rs.getLong("id")),避免数据库列顺序变更导致的错误,提升可读性 - Java 8+可使用Lambda简化
ResultSetExtractor写法:
public List<Contato> getAllContatos() { return template.query("select * from CONTATO", rs -> { List<Contato> list = new ArrayList<>(); while (rs.next()) { Contato e = new Contato(); e.setId(rs.getLong("id")); e.setNome(rs.getString("nome")); e.setEmail(rs.getString("email")); e.setTelefone(rs.getString("telefone")); list.add(e); } return list; }); }
内容的提问来源于stack exchange,提问作者Paulo Cesar Pereira da costa
相关产品推荐
相关产品推荐

