How can I map a resultset from a few tables into a complex object?
let me elaborate:
Lets say I have these 2 classes:
public class User {
private int user_id;
private String fname;
private String lname;
//getters setters...
}
public class Country{
private String country;
private ArrayList users;
}
The sql query:
SELECT * FROM users U, Country C WHERE c.user_id = U.id
gives me the following output -
id | fname | lname| country
1 | Jack | Levi | USA
1 | Jack | Levi | UK
2 | Mike | Brown| Germany
How can I map these results into the Country class?
I need make from it a Json string to get something like this:
{
id : 1,
fname: "jack",
lname" "levi",
countries : {"USA", "UK"}
}
Thank you very much!!
解决方案
Create a HashMap of where user id is the key, and user is the value. Then when you process the result set, do map.get(resultset.get(userid)), if it's null, create a new user, but if it isn't then do the logic to append a user to the country.
HashMap users;
HashMap countries;
//inside the result set processing
User u = users.get(resultSet.get("id"));
if(null != u) {
//populate user here
} else {
Country c = countries.get(resultSet.get(country);
c.users.add(u);
}