在Java中 - 如何将resultSet映射到复杂对象? [英] In Java - How to map resultSet into a complex object?
问题描述
如何将结果集从几个表映射到复杂对象?
让我详细说明:
How can I map a resultset from a few tables into a complex object? let me elaborate:
假设我有这两个类:
public class User {
private int user_id;
private String fname;
private String lname;
//getters setters...
}
public class Country{
private String country;
private ArrayList<User> users;
}
sql
查询:
SELECT * FROM users U,Country C WHERE c.user_id = U.id
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
如何将这些结果映射到Country类?
我需要从它得到一个 Json
字符串来得到这样的东西:
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"}
}
非常感谢!!
推荐答案
创建一个HashMap,其中user id是键,user是值。然后在处理结果集时,执行map.get(resultset.get(userid) ),如果它为null,则创建一个新用户,但如果不是,则执行逻辑将用户附加到该国家。
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<Integer, User> users;
HashMap<String, Country> 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);
}
这篇关于在Java中 - 如何将resultSet映射到复杂对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!