[英]Spring 3.x + SimpleJdbcTemplate : Returning multiple columns
我在Spring 3.x
使用SimpleJdbcTemplate
。 為了獲得單列,我使用下面的代碼,它可以正常工作:
public String selectSingleColumn(int deptId){
return jdbcTemplate.queryForObject("SELECT DEPT_NAME FROM DEPT WHERE DEPT_ID = ?", String.class, deptId);
}
問題:
我想從上面的表中獲取多個列,例如DEPT_NAME
和DEPT_CODE
(但不是所有屬於該表的列),如何修改上面的代碼來完成? 在這種情況下,我對queryForObject
的second parameter
感到困惑; 理想情況下,我認為應該是Object[]
但stilll感到困惑。 請指導我。
我只需要查詢整個域對象,而不必為不同的列編寫不同的查詢。 首先,它使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)為部門創建域對象
public class Department{
private String departmentName;
private String departmentCode;
//getters and setters omitted for brevity
}
(2)創建一個RowMapper類以將結果集映射到Department Object
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 ());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.