Reputation: 9
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"}
}
Upvotes: 1
Views: 1345
Reputation: 17460
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;
}
Upvotes: 2