Search code examples
javaspring-wsjdbctemplate

Return Type for jdbcTemplate.queryForList(sql, object, classType)


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});

The SQL query is:

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()); 
}

I get an error:

java.util.LinkedHashMap cannot be cast to net.org.messagehistory.model.Conversation

How do I convert this linkedMap into the desired Object??

Thanks


Solution

  • 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) off 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;
            }
        });