jdbcTemplate.queryForList的返回类型(sql,object,classType) [英] Return Type for jdbcTemplate.queryForList(sql, object, classType)
问题描述
我正在使用jdbcTemplate.queryForList以下列方式执行命名查询:
I'm executing a named query using jdbcTemplate.queryForList in the following manner:
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 ?)";
但是当按以下方式提取列表内容时:
But when extracting the content of the list in the following manner:
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转换为所需的对象??
How do I convert this linkedMap into the desired Object??
谢谢
推荐答案
为了将查询的结果集映射到特定的Java类,您可能最好(假设您有兴趣在其他地方使用该对象)使用RowMapper将结果集中的列转换为对象实例。
In order to map a the result set of query to a particular Java class you'll probably be best (assuming you're interested in using the object elsewhere) of with a RowMapper to convert the columns in the result set into an object instance.
See Section 12.2.1.1 of Data access with JDBC on how to use a row mapper.
简而言之,你'我需要这样的东西:
In short, you'll need something like:
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;
}
});
这篇关于jdbcTemplate.queryForList的返回类型(sql,object,classType)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!