SpringBoot JPA, 一对多、多对一的用法,折腾了好几天,总算弄明白些了。
写法非常简洁,代码量很少,开发效率上的优势很明显。整理了如下:
实体:一:DetectUnit(站点) , 多: Device(设备), 一个站点上配备多台设备。
一对多 OneToMany: DetectUnit.java
//@JsonBackReference //json中排除
@OneToMany(targetEntity=Device.class, mappedBy="detectUnit")
private List<Device> devices;
//setter, getter
查询结果:
{
"id": 1,
"no": "001",
"name": "碧溪检测站",
"devices": [
{
"id": 3,
"no": "000111",
"name": "碧溪1号机",
"deployTime": "2015-01-13"
},
{
"id": 7,
"no": "0188",
"name": "汽渡5号机",
"deployTime": "2016-08-12"
},
...
]
}
多对一 ManyToOne: Device.java
//@JsonBackReference //json中排除
@ManyToOne
private DetectUnit detectUnit;
//setter, getter
查询结果:
[
{...}
{
"id": 5,
"no": "ML002",
"name": "梅李镇2号机",
"deployTime": "2015-01-12",
"detectUnit": {
"id": 2,
"no": "002",
"name": "梅李检测站"
}
}
{...}
]
注意点:
@JsonBackReference 表示生成json时该属性排除
实体A和实体B存在一多关系:
A和B中,至少有一方要带@JsonBackReference,否则会引起Infinite Recursion的问题,导致死循环。
参考:https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion