Reputation: 3728
I am not able to set the data from ResultSet to HashMap.
My Query is returning 4 records, but HashMap is holding Last 2 records only. However, in the loop I am able to print 4 records data. Can any one help?
Here is my code:
workOrderMap=new HashMap<String, Integer>();
Statement statement = serviceconnection.createStatement();
ResultSet rs = statement.executeQuery("SELECT OPERATION,WORKORDERID FROM History WHERE OPERATION='CREATE'OR OPERATION='UPDATE'");
workOrderMap=new HashMap<String, Integer>();
while (rs.next()) {
workOrderMap.put(rs.getString("OPERATION"), rs.getInt("WORKORDERID"));
System.out.println(rs.getString("OPERATION")); // loops 4 times
}
System.out.println("List of Workorder id's" + workOrderMap.size()); // prints 2
Upvotes: 1
Views: 3343
Reputation: 424983
There are only 2 distinct values returned from rs.getString("OPERATION")
.
This is hardly surprising, considering your WHERE
clause only allows there to be 2 values:
WHERE OPERATION='CREATE' OR OPERATION='UPDATE'
In a Map
, the keys are unique, so calling put()
with the same key value will overwrite the value previously there.
When converting rowsets to a POJO, I prefer creating a List<Map<String, Object>>
- each element of the list is a row, each entry in the associated Map are the column names and their values.
FYI, your WHERE
clause can be written more elegantly as:
WHERE OPERATION IN ('CREATE', 'UPDATE')
Upvotes: 1
Reputation: 350
Since the keys are same, You will see only 2 values in hashmap.
Example
Map<String,Integer> workOrderMap=new HashMap<String, Integer>();
workOrderMap.put("S", 1);
workOrderMap.put("S", 1);
workOrderMap.put("S2", 1);
System.out.println(workOrderMap.size());
OUTPUT : 2
Upvotes: 1