В вашем VehicleStatus
свойстве json для шин указано vehicleTire
, а в json - tires
, поэтому всегда имеет значение null, поэтому вы должны добавить @JsonProperty(value="tires")
.
Вотполный код:
@Entity
public class VehicleStatus implements Serializable{
@Id
private String vin;
private Double latitude;
private Double longitude;
private Double fuelVolume;
private int speed;
private int engineHp;
private int engineRpm;
private boolean checkEngineLightOn;
private boolean engineCoolantLow;
private boolean cruiseControlOn;
@OneToOne(mappedBy = "vehicleStatus",cascade=CascadeType.ALL)
@JoinColumn(name = "id")
@JsonProperty(value="tires") // here is the key :)
private Tires vehicleTire;
// Getters && Setters
}
@Entity
public class Tires implements Serializable{
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
Integer id;
private Integer frontLeft; // NB try always to use wrapper type rather than primitive in jpa
private Integer frontRight;
private Integer rearLeft;
private Integer rearRight;
@OneToOne
private VehicleStatus vehicleStatus;
// Getters && Setters
}
Репозиторий шин:
public interface TiresRepository extends JpaRepository<Tires, Integer>{
}
Репозиторий VehicleStatus:
public interface VehicleStatusRepository extends JpaRepository<VehicleStatus, String>{
}
Пример контроллера:
@RestController
@RequestMapping
class MyController {
@Autowired
private VehicleStatusRepository vehicleStatusRepository;
@RequestMapping(method = RequestMethod.POST, value = "/readings")
public void readVehicleStatus(@RequestBody VehicleStatus vehicleStatus){
vehicleStatusRepository.saveAndFlush(vehicleStatus);
}
}
Основной класс:
@SpringBootApplication
@EnableAutoConfiguration
public class SpringStackOverflowSolutionApplication {
public static void main(String[] args) {
SpringApplication.run(SpringStackOverflowSolutionApplication.class, args);
}
}
Примечание: не забудьте cascadeAll, иначе объект шин не будет сохранен в базе данных, и вы получите следующее исключение:
org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : package.VehicleStatus.vehicleTire -> package.Tires