jdbcTemplate.queryForList(sql,object,classType)的返回类型
问题内容:
我正在以以下方式使用jdbcTemplate.queryForList执行命名查询:
List<Conversation> conversations = jdbcTemplate.queryForList(
SELECT_ALL_CONVERSATIONS_SQL_FULL,
new Object[] {userId, dateFrom, dateTo});
SQL查询为:
private final String SELECT_ALL_CONVERSATIONS_SQL_FULL =
"select conversation.conversationID, conversation.room, " +
"conversation.isExternal, conversation.startDate, " +
"conversation.lastActivity, conversation.messageCount " +
"from openfire.ofconversation conversation " +
"WHERE conversation.conversationid IN " +
"(SELECT conversation.conversationID " +
"FROM openfire.ofconversation conversation, " +
"openfire.ofconparticipant participant " +
"WHERE conversation.conversationID = participant.conversationID " +
"AND participant.bareJID LIKE ? " +
"AND conversation.startDate between ? AND ?)";
但是,当以以下方式提取列表的内容时:
for (Conversation conversation : conversations) {
builder.append(conversation.getId());
builder.append(",");
builder.append(conversation.getRoom());
builder.append(",");
builder.append(conversation.getIsExternal());
builder.append(",");
builder.append(conversation.getStartDate());
builder.append(",");
builder.append(conversation.getEndDate());
builder.append(",");
builder.append(conversation.getMsgCount());
out.write(builder.toString());
}
我收到一个错误:
java.util.LinkedHashMap cannot be cast to net.org.messagehistory.model.Conversation
如何将这个linkedMap转换为所需的对象?
谢谢
问题答案:
为了将查询的结果集映射到特定的Java类,最好使用RowMapper将结果集中的列转换为对象实例(假设您对在其他地方使用该对象感兴趣)。
有关如何使用行映射器的信息,请参见第12.2.1.1节“使用JDBC进行数据访问”。
简而言之,您将需要以下内容:
List<Conversation> actors = jdbcTemplate.query(
SELECT_ALL_CONVERSATIONS_SQL_FULL,
new Object[] {userId, dateFrom, dateTo},
new RowMapper<Conversation>() {
public Conversation mapRow(ResultSet rs, int rowNum) throws SQLException {
Conversation c = new Conversation();
c.setId(rs.getLong(1));
c.setRoom(rs.getString(2));
[...]
return c;
}
});