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 (将#修改为@)