我是Spring框架的新手。目前陷入困境。所以基本上我想用一些信息检索员工列表。我有两个表,一个是员工数据,另一个是员工赢得的奖励。现在我想要获得奖项的员工名单。我正在尝试这样做。
public ArrayList<Employee> getAwrdDist() {
String sql = "SELECT DISTINCT a.`Idcode`,a.`Name` FROM `gen_profile` a, `awards_received` b WHERE a.`Idcode`=b.`IDCODE`";
ArrayList<Employee> arrEmp = new ArrayList<Employee>();
arrComt = (ArrayList<Employee>) jdbcTemplate.query(sql, new RowMapper<Employee>(){
@Override
public Employee mapRow(ResultSet rs, int arg1) throws SQLException {
Employee objEmp = new Employee();
objEmp.setIdcode(rs.getString("Idcode"));
objEmp.setName(rs.getString("Name"));
String awrdSql = "SELECT a.`AWARD_NAME`,a.`AWARDING_BODY`,a.`AWARD_DATE` FROM `awards_received` a"+
" WHERE a.`IDCODE`="+objEmp.getIdcode();
ArrayList<Award> arrWonAwards = new ArrayList<Award>();
arrWonAwards = (ArrayList<Award>) jdbcTemplate.query(sql, new RowMapper<Award>(){
@Override
public AwardmapRow(ResultSet rs, int arg1) throws SQLException {
Award wonAward = new Award();
wonAward.setAwrdNm(rs.getString("AWARD_NAME"));
wonAward.setAwrdBody(rs.getString("AWARDING_BODY"));
wonAward.setAwrdDt(rs.getString("AWARD_DATE"));
return wonAward ;
}
});
objEmp.setArrWonAwrds(arrWonAwards);
return objEmp;
}
});
return arrComt;
}
请帮助我解决这个问题。
答案 0 :(得分:0)
基本上,您应该使用一个查询,该查询返回员工的奖励列表。这应该给你一个有1emp的结果集 - 许多奖项结构。为此,您可以使用ResultSetExtractor来获取以下代码片段的详细信息:
String sql = "SELECT DISTINCT a.`Idcode`,a.`Name` FROM `gen_profile` a, `awards_received` b WHERE a.`Idcode`=b.`IDCODE`";
ArrayList<Employee> arrEmp = new ArrayList<Employee>();
arrComt = (ArrayList<Employee>) jdbcTemplate.query(sql, new ResultSetExtractor<List<Employee>>(){
@Override
public List<Employee> extractData(ResultSet rs) throws SQLException {
Map<String, Employee> mapEmp = new LinkedHashMap<>();
while (rs.next()) {
String key = rs.getString("Idcode");
if (mapEmp.containsKey(key)) {
Award wonAward = new Award();
wonAward.setAwrdNm(rs.getString("AWARD_NAME"));
wonAward.setAwrdBody(rs.getString("AWARDING_BODY"));
wonAward.setAwrdDt(rs.getString("AWARD_DATE"));
Employee emp = mapEmp.get(key)
emp.getArrWonAwrds().add(wonAward);
} else {
Employee objEmp = new Employee();
objEmp.setIdcode(key);
objEmp.setName(rs.getString("Name"));
mapEmp.put(key, objEmp);
}
}
return mapEmp.getValues();
}
});
return arrComt;
要使用上面的代码,您应该修改您的查询:
SELECT DISTINCT a.`Idcode`,a.`Name`,
b.`AWARD_NAME`,b.`AWARDING_BODY`,b.`AWARD_DATE`
FROM `gen_profile` a JOIN `awards_received` b ON (b.`IDCODE` = a.`Idcode`)
WHERE a.`Idcode`=b.`IDCODE`