如何解决Spring Data JPA - 在创建期间将嵌套对象与父对象链接
我正在尝试使用 OnetoMany 关系创建一个带有嵌套“MeasurementDetail”列表的新“Measurement”对象。
自动生成两个新对象的 Id,数据保存在数据库中,但 MeasurementDetail 行缺少对父级 (Measurement) 的引用。
id | 类型 | 价值 | measurement_id |
---|---|---|---|
3 | pm2.5 | 5 | [NULL] |
4 | pm10 | 7 | [NULL] |
我不知道如何告诉 spring 动态链接对象,我显然错过了……
提前致谢!
Measurement.java:
@Entity
public class Measurement implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@OnetoMany(
mappedBy = "measurement",cascade = CascadeType.ALL,orphanRemoval = true
)
private List<MeasurementDetail> measurementDetailList = new ArrayList<>();
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "location_id")
@JsonIgnoreProperties({"hibernateLazyInitializer","handler"})
private Location location;
//standard constructor,getters,setters...
MeasurementDetail.java:
@Entity
public class MeasurementDetail {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
long id;
String type;
long value;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "measurement_id")
@JsonIgnoreProperties({"hibernateLazyInitializer","handler"})
private Measurement measurement;
//standard constructor,setters...
MeasurementController.java:
...
@PostMapping("locations/{id}/measurements")
Measurement newMeasurement(@PathVariable long id,@RequestBody Measurement newMeasurement) {
Location location = loc.getById(id);
newMeasurement.setLocation(location);
return repository.save(newMeasurement);
}
...
curl --location --request POST 'localhost:8080/locations/1/measurements' \
--header 'Content-Type: application/json' \
--data-raw '{
"measurementDetailList":[
{
"type": "pm2.5","value": 5
},{
"type": "pm10","value": 7
}
]
}'
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。