表1,人物表A,id为主键
id | name |
---|---|
1 | 小王 |
2 | 小李 |
表2,物品表B uid为主键
uid | item | belong |
---|---|---|
1 | 尺子 | 1 |
2 | 铅笔 | 1 |
3 | 橡皮 | 2 |
4 | 圆规 | 2 |
5 | 墨水 | 2 |
表A和表B通过表B的belong字段和表A的id字段关联
经过观察,orm框架里sql的实现方式如下
select t.*,b.uid,b.item from A t left join B r on t.id=r.belong
得到如下表
id | name | item | uid |
---|---|---|---|
1 | 小王 | 1 | 尺子 |
1 | 小王 | 2 | 铅笔 |
2 | 小李 | 3 | 橡皮 |
2 | 小李 | 4 | 圆规 |
2 | 小李 | 5 | 墨水 |
实体类定义如下
//归属物品
public class Belong{
public int uid;
public String item;
}
//人员
public class Result{
public int id;
public String name;
public Belong[] belongs;
}
返回的json如下
[{
"id":1,
"name":"小王",
"belongs":[{
"uid":1,
"item":"尺子"
},{
"uid":2,
"item":"铅笔"
}]
},{
"id":2,
"name":"小李",
"belongs":[{
"uid":3,
"item":"橡皮"
},{
"uid":4,
"item":"圆规"
},{
"uid":5,
"item":"墨水"
}]
}]
不知道在座各位有没有考虑过,sql结果是如何根据实体类结构生成对应的json数据的
本人在此猜想,实际上是对jdbc返回的查询结果集遍历,每次都查找是否已经存在对应id,name的人物对象,如果没有,那就生成,如果有,那就对生成belong并添加到对应人物对象的belongs中
具体代码实现放在下篇