ga如图是我的数据库列名
与Employee类字段不匹配
直接使用BeanPropertyRowMapper会导致失败。
解决方法如下。
创建一个子类继承BeanPropertyRowMapper,覆写其中的mapRow方法
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
public class MyRowMapper extends BeanPropertyRowMapper<Employee>{
public MyRowMapper(Class<Employee> mappedClass) {
super(mappedClass);
}
public Employee mapRow(ResultSet resultSet, int rowNumber) throws SQLException, DataAccessException {
String name = resultSet.getString("ename");
String address = resultSet.getString("address");
String phone = resultSet.getString("phone");
double salary = resultSet.getDouble("salary");
int type = resultSet.getInt("etype");
Employee employee = new Employee(name, address, phone, salary, type);
return employee;
}
}
调用时将
new BeanPropertyRowMapper<>(Employee.class)
替换为
new MyRowMapper(Employee.class)
即可,以下是实际调用的代码
public List<Employee> getEmployees( ) {
return jdbcTemplate.query("SELECT * FROM employee",new MyRowMapper(Employee.class)
);
}