Let's say there are 2 tables: PERSON and TELEPHONE.
A person can have more than one telephone. A telephone number can only be owned by one person.
When I join both table, the resultset returned is
P_ID NAME TEL_NO
1 ALVIN 911
1 ALVIN 912
1 ALVIN 913
2 ERIC 922
2 ERIC 923
But in my HTML, I want to show the page as:
ID: 1 Name : ALVIN TEL_NO: 911, 912, 913
ID: 2 Name : ERIC TEL_NO: 922, 923
What is the most efficient way to read the resultset and show the the data as shown above?
If I loop through the ResultSet and print it on the page. It would have multiple row with same name which are ALVIN and ERIC. But I want to print all the TEL_NO of same person on the same row.
I have a Java class that store the PERSON details.
public class Person {
public int id;
public String name;
public List<Integer> telNos = new ArrayList<Integer>();
}
List<Person> persons = new ArrayList<Person>;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
while(resultSet.next()) {
int pId = resultSet.getInt("P_ID");
String name = resultSet.getString("NAME");
int telNo = resultSet.getInt("TEL_NO");
if(map.containsKey(pId)){
Person person = persons.get(map.get(pId));
person.telNos.add(telNo);
} else {
Person person = new Person();
person.id = pId;
person.name = name;
person.telNos.add(telNo);
map.put(pId, persons.size());
persons.add(person);
}
}
Finally, I pass the persons to the JSP for display.
My question is that: is there better way to loop and display the ResultSet without having same P_ID on different row of the html table.