我正在使用SimpleJdbcTemplate
Spring 3.x
。为了获得单个列,我使用下面的代码,它工作正常:
public String selectSingleColumn(int deptId){
return jdbcTemplate.queryForObject("SELECT DEPT_NAME FROM DEPT WHERE DEPT_ID = ?", String.class, deptId);
}
问题:
我想从上面的表中获取多个列,例如DEPT_NAME
和DEPT_CODE
(但不是所有属于该表的列),如何修改上面的代码来完成它?在这种情况下,我对second parameter
的{{1}}感到困惑;理想情况下,我认为它应该是queryForObject
但仍然困惑。请指导我。
答案 0 :(得分:2)
我只是查询整个域对象,而不必为不同的列编写不同的查询。首先,它使dao更可重复使用。
例如:
部门域对象
public class Department {
private long id;
private String deptName;
private String deptCode;
// other fields
// getters and setters
}
DepartmentDao
public class DepartmentDaoImpl extends JdbcTemplate implements DepartmentDao {
private static final String DEPT_BY_ID
= "select * from DEPARTMENT where DEPT_ID = ?";
@Override
public Department getDepartmentById(long id) {
return (Department) queryForObject(
DEPT_BY_ID,
new Object[] { id },
new RowMapper<Department>() {
@Override
public Department mapRow(ResultSet rs, int rowNumber) {
Department dept = new Department();
dept.setId(rs.getLong("DEPT_ID");
dept.setDeptName(rs.getString("DEPT_NAME");
dept.setDeptCode(rs.getString("DEPT_CODE");
// set other properties
return dept;
}
});
}
}
如果你真的只想要两列,你可以使用queryForMap
public class TestCustomerDao extends JdbcTemplate implements DepartmentDao {
private static final String FOR_MAP
= "select DEPT_NAME,DEPT_CODE from DEPARTMENT where DEPT_ID = ?";
@Override
public Map<String, Object> getCoupleColumnsById(long id) {
return (Map<String, Object>)queryForMap(FOR_MAP, new Object[] {id});
}
}
地图将以
的形式返回 key value
DEPT_NAME = value
DEPT_CODE = value
答案 1 :(得分:0)
以下是执行此操作的步骤 -
(1)为部门
创建域对象public class Department{
private String departmentName;
private String departmentCode;
//getters and setters omitted for brevity
}
(2)创建一个RowMapper类,将结果集映射到Department对象
public class DepartmentRowMapper implements RowMapper<Department>
{
public Department mapRow(ResultSet rs, int rowNum) throws SQLException {
Department department= new Department ();
department.setDepartmentName(rs.getString("DEPT_NAME"));
department.setDepartmentCode(rs.getString("DEPT_CODE"));
return department;
}
}
(3)创建Dao类
public class DepartmentDao
private JdbcTemplate jdbcTemplate;
//getters and setters omitted for brevity
public Department getDepartment(int deptId){
return (Department)jdbcTemplate.queryForObject("SELECT DEPT_NAME FROM DEPT WHERE DEPT_ID = ?",new Object[] {deptId}, new DepartmentRowMapper ());
}
}