I have a sql statement that brings back the following rows:
I would like to obtain these values from a JDBC result set as two objects. One for the customer with customerNo 1 and the other for customer 2. I would like the two objects to have another array value with the related Titles with the object values.
The structure would ultimately look like this (in JSON):
{customerNo : 1, ["Object 1", "Object 2", "Object 3"]}, {customerNo : 2, ["Object 4", "Object 5"]}
How can I accomplish this with JDBC?
解决方案
You can use a Map to initially collect the results in the format you want.
Map> customerTitles = new HashMap>();
while(resultSet.next()) {
Integer custId = resultSet.getInt(1);
Set titles = customerTitles.containsKey(custId) ?
customerTitles.get(custId) : new HashSet();
titles.add(resultSet.getString(2));
customerTitles.put(custId, titles);
}
Once you have it collected this way, you can iterate over the Map and in turn the Sets within and convert them to JSON
// Convert to Json array here using your JSON library
for(Integer custId : customerTitles.keySet()) {
for(String title : customerTitles.get(custId)) {
}
}