0

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
        }
    ]
}'
  • I can't see you are adding measurementDetails in the object before saving. – Pirate Jun 19 '21 at 08:02
  • @Pirate thanks, it did cross my mind, but I'm not quite sure how I should do it. MeasurementDetail list is part of the Measurement body.. maybe it should me modelled differently.. – Krzysztof Sam Jun 19 '21 at 09:34
  • Found the answer here: https://stackoverflow.com/questions/21058570/how-to-save-nested-json-object-in-a-spring-mvc – Krzysztof Sam Jun 20 '21 at 10:19

0 Answers0