【发布时间】:2021-05-19 07:46:59
【问题描述】:
我有 2 张桌子。
DATA
+------+--------+---------------------+------------+
| ID | Name | Desc | Type |
+------+--------+---------------------+------------+
| 1001 | Motor | Main motor 50 volt | Mechanical |
| 1002 | Nut | 25 mm dia | Mechanical |
| 1003 | Bolt | Hexa bolt | Mechanical |
| 1004 | Engine | 750cc liquid cooled | Mechanical |
| 1005 | Oil | 1 liter | NA |
| 1006 | Filter | Airfilter | NA |
| 1007 | AC | 1000w | Electrical |
+------+--------+---------------------+------------+
Relationship
+-----------+-----------+----------+
| Parent_id | Relation | Child_id |
+-----------+-----------+----------+
| 1001 | Accessory | 1002 |
| 1001 | Accessory | 1003 |
| 1001 | Service | 1005 |
| 1001 | Service | 1006 |
| 1004 | Accessory | 1002 |
| 1004 | Accessory | 1003 |
| 1004 | Service | 1005 |
+-----------+-----------+----------+
当用户搜索1001时,我想提供以下响应
{
"id": "1001",
"name": "Motor",
"desc": "Main motor 50 volt",
"Accessory": [{
"id": "1002",
"name": "Nut"
},
{
"id": "1003",
"name": "Bolt"
}
],
"Service": [{
"id": "1005",
"name": "Oil"
},
{
"id": "1006",
"name": "Filter"
}
]
}
这里的Accessory 和Service 来自relationship 表列relation。我对弹簧靴一无所知。在谷歌的帮助下,我完成了以下代码。这给了我一个级别的 json。但我无法找到如何创建这个嵌套的 JSON。请提供一些建议。
存储库:
@Repository
public interface MyDataRepo extends JpaRepository<Items, String> {
@Query(value="SELECT D.id,D.name,D.desc,R.relation,R.child_id as childid,DC.name as childname
FROM DATA D
JOIN RELATIONSHIP R ON D.ID=R.PARENT_ID
JOIN DATA DC ON DC.id=R.CHILD_ID
WHERE D.ID=?1",nativeQuery=true)
List<Data> findAllCategory(String id);
public static interface Data {
String getid();
String getname();
String getdesc();
String getrelation();
String getchildid();
String getchildname();
}
}
服务:
public List<Data> getMyData(String id) {
return repo.findAllCategory(id);
}
控制器:
@GetMapping("/getData/{id}")
public ResponseEntity<List<Data>> retrieveData(@PathVariable String id) {
List<Data> stud = service.getMyData(id);
return ResponseEntity.ok().body(stud);
}
【问题讨论】:
标签: java json spring-boot spring-data-jpa nativequery