I'm trying to create a new "Measurement" object with a nested "MeasurementDetail" list using OneToMany relation.
Ids for both new objects are automatically generated, the data is persisted in the db, but the MeasurementDetail rows miss the reference to parent (Measurement).
id | type | value | measurement_id |
---|---|---|---|
3 | pm2.5 | 5 | [NULL] |
4 | pm10 | 7 | [NULL] |
I'm not sure how to tell spring to link the objects on the fly, I'm clearly missing sth..
Thanks in advance!
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, getters, 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
}
]
}'