1

I have Sensor Entity has Relationship to Location Entity

@RequiredArgsConstructor @Data public class TemperatureSensor { @Id @GeneratedValue(strategy = AUTO) private Long id; private float temperature; private float min; private float max; private float timeInterval; private boolean activityState; @OneToOne private Location location; } 
@Entity @Data @RequiredArgsConstructor public class Location { @Id @GeneratedValue(strategy = AUTO) private Long id; private Long coordinates; private String name; private EnvironmentState environmentState = EnvironmentState.NORMAL_CASE; @OneToOne private TemperatureSensor temperatureSensor; } 

I created two endpoints to initiate each entity, so I send Sensor object using Postman like this and get location_id null in the database. The same is happening with Location.

 { "temperature" : "15.2", "min" :"9.0", "max" : "20.0", "timeInterval" : "552.5", "activityState" : "true", "location_id" :"1" } 

Also, I tried to send location object and I got the exception: object references an unsaved transient instance - save the transient instance before flushing

{ "temperature" : "15.2", "min" :"9.0", "max" : "20.0", "timeInterval" : "552.5", "activityState" : "true", "location" :{"coordinates": "123","name" : "loc01"} } 

1 Answer 1

2

The issue seems to be that you are missing cascade options on your @OneToOne annotations. Try using @OneToOne(cascade = CascadeType.ALL) instead (this will cascade all operations PERSIST, MERGE, REMOVE, REFRESH, DETACH to the other entity).

@RequiredArgsConstructor @Data public class TemperatureSensor { @Id @GeneratedValue(strategy = AUTO) private Long id; private float temperature; private float min; private float max; private float timeInterval; private boolean activityState; @OneToOne(cascade = CascadeType.ALL) private Location location; } 
Entity @Data @RequiredArgsConstructor public class Location { @Id @GeneratedValue(strategy = AUTO) private Long id; private Long coordinates; private String name; private EnvironmentState environmentState = EnvironmentState.NORMAL_CASE; @OneToOne(cascade = CascadeType.ALL) private TemperatureSensor temperatureSensor; } 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it works! but I still need to pass the whole object. how can I pass only the foreign key
To my knowledge, there is no way to have that automated. If the given location_id already exists, then you need to actively retrieve it from the database and set it to the received TemperatureSensor. Unless you want to have a custom persist query for your TemperatureSensor but I am not sure that is the best option.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.