I have a problem on retrieving data from DB.
This is my method from DAO
@MapKey("key")
public Map<String, Integer> getMeasurementsPerNode() throws SQLException;
There is mapper
<select id="getMeasurementsPerNode" resultType="hashmap">
SELECT
w.wd_ip AS `key`,
COUNT(m.id) AS `value`
FROM t_workers w
LEFT JOIN t_measurements m ON w.id = m.worker_id AND m.measurement_timestamp <![CDATA[>]]> DATE_SUB(NOW(), INTERVAL 1 HOUR)
WHERE w.active = 1
AND w.worker_type_id = 1
GROUP BY w.wd_ip
ORDER BY `value` DESC
</select>
My problem is when I want to use obtained value from map as Integer I get ClassCastException
(Hashmap
to Integer
). Can you please help me.
This is loop where I use it:
protected Map<String, Integer> nodeMeasurementsCount = nodeMapper.getMeasurementsPerNode();
for (Map.Entry<String, Integer> nodeThread : nodeMeasurementsCount.entrySet()) {
NodeRestartCounter nrc = new NodeRestartCounter();
nrc.setNode(nodeThread.getKey());
nrc.setMeasurementCount(nodeThread.getValue());
nodeRestartCounterList.add(nrc);
}
You cannot do such kind of mapping.
The key and value in a Hashmap is contained in an Map.Entry object and cannot be directly mapped via SqlMaps.
https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html
When you mention the result type as hashmap (java.util.HashMap)
, the result is always a list of HashMap with each each map containing the column names as keys and their corresponding values as column values for a particular row.