java resultset 映射到实例,在Java中 - 如何将resultSet映射到复杂对象?

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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值