我有一个返回表的查询。查询是:
SELECT * FROM vote_votes WHERE poll_id=? ORDER BY option_id ASC
例如,当poll_id为1时,该表应为:
poll_id | option_id | option_text
-------------------------------------
1 1 one
1 2 two
. . .
. . .
. . .
1 10 ten
现在在我的rest控制器中,我希望有一个方法可以将上述查询作为json.something返回。
@ResponseBody
@RequestMapping(value = "/polls/{id}", method = RequestMethod.GET)
public Poll getOptions(int id) {
return pollDao.getPollOptionsById(id);
}
我已经有一个名为Poll的POJO,它具有诸如poll_id,option_id,option_text,title,description和其他内容的属性。 我所做的是这样:
private static final String SQL_GET_PollOptions_BY_ID = "SELECT * FROM vote_votes WHERE poll_id=? ORDER BY option_id ASC";
public Poll getPollOptionsById(int id) {
try {
List<Poll> poll = (List<Poll>) jdbcTemplate.query(SQL_GET_PollOptions_BY_ID, new PollOptionsExtractor(), id);
return poll.get(0);
} catch (EmptyResultDataAccessException | IndexOutOfBoundsException e) {
return null;
}
}
private static class PollOptionsExtractor implements ResultSetExtractor {
@Override
public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
Map<Integer, Poll> map = new LinkedHashMap<>();
Poll poll = null;
while (rs.next()) {
int id = rs.getInt("poll_id");
int opt_id = rs.getInt("option_id");
poll = map.get(id);
if (poll == null) {
String opt_text = rs.getString("option_text");
poll = new Poll(id, opt_id, opt_text);
map.put(id, poll);
}
}
return new ArrayList<>(map.values());
}
}
但是当我转到localhost:8080/polls/{id}
时,我只能看到每个poll_id的第一个option_id和option_text。
请注意,最多可以有20个选项。
如何获得特定poll_id的所有选项,而不仅仅是一个?