Я пытаюсь сохранить вложенный объект json, полученный через HTTP-запрос POST, к базе данных с использованием данных Spring. Я создал два класса сущностей "vehicleReadings.class" и "tyres.class".
Я создал все контроллеры, сервисный уровень и уровень репозитория для этих классов. В классе vehicleReadings я создал объект шин с аннотацией @OnetoOne. когда я запускаю код, все данные сохраняются в таблице vehicleReadings, и ни одна не сохраняется в таблице шин.
таблицы создаются с зависимостью внешнего ключа. Таблица vehicleReadings содержит все столбцы и один дополнительный столбец tyres_id. при сохранении данных все столбцы заполнены, но tyre_id оставлено нулевым, а таблица шин не заполнена.
Я предоставляю весь код ниже для справки.
Объект JSON, полученный по запросу POST:
{
"vin": "1HGCR2F3XFA027534",
"latitude": 41.803194,
"longitude": -88.144406,
"timestamp": "2017-05-25T17:31:25.268Z",
"fuelVolume": 1.5,
"speed": 85,
"engineHp": 240,
"checkEngineLightOn": false,
"engineCoolantLow": true,
"cruiseControlOn": true,
"engineRpm": 6300,
"tires": {
"frontLeft": 34,
"frontRight": 36,
"rearLeft": 29,
"rearRight": 34
}
}
Я создал два класса сущностей "vehicleReadings" и "tyres"
vehicleReadings.class
package springproject.entity;
import javax.persistence.*;
import java.sql.Timestamp;
@Entity
public class vehicleReadings {
@Id
private String vin;
private float latitude;
private float longitude;
private Timestamp timestamp;
private float fuelVolume;
private int speed;
private int engineHP;
private boolean checkEngineLightOn;
private boolean engineCoolantLow;
private boolean cruiseControlOn;
private int engineRpm;
@OneToOne
@JoinColumn
private tires tire;
public vehicleReadings(){
}
public tires getTire() {
return tire;
}
public void setTire(tires tire) {
this.tire = tire;
}
public String getVin() {
return vin;
}
public void setVin(String vin) {
this.vin = vin;
}
public float getLatitude() {
return latitude;
}
public void setLatitude(float latitude) {
this.latitude = latitude;
}
public float getLongitude() {
return longitude;
}
public void setLongitude(float longitude) {
this.longitude = longitude;
}
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
public float getFuelVolume() {
return fuelVolume;
}
public void setFuelVolume(float fuelVolume) {
this.fuelVolume = fuelVolume;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getEngineHP() {
return engineHP;
}
public void setEngineHP(int engineHP) {
this.engineHP = engineHP;
}
public boolean isCheckEngineLightOn() {
return checkEngineLightOn;
}
public void setCheckEngineLightOn(boolean checkEngineLightOn) {
this.checkEngineLightOn = checkEngineLightOn;
}
public boolean isEngineCoolantLow() {
return engineCoolantLow;
}
public void setEngineCoolantLow(boolean engineCoolantLow) {
this.engineCoolantLow = engineCoolantLow;
}
public boolean isCruiseControlOn() {
return cruiseControlOn;
}
public void setCruiseControlOn(boolean cruiseControlOn) {
this.cruiseControlOn = cruiseControlOn;
}
public int getEngineRpm() {
return engineRpm;
}
public void setEngineRpm(int engineRpm) {
this.engineRpm = engineRpm;
}
}
tires.class
package springproject.entity;
import javax.persistence.*;
import java.util.UUID;
@Entity
public class tires {
@Id
private String id;
private int frontLeft;
private int frontRight;
private int rearLeft;
private int rearRight;
public tires(){
this.id = UUID.randomUUID().toString();
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public int getFrontLeft() {
return frontLeft;
}
public void setFrontLeft(int frontLeft) {
this.frontLeft = frontLeft;
}
public int getFrontRight() {
return frontRight;
}
public void setFrontRight(int frontRight) {
this.frontRight = frontRight;
}
public int getRearLeft() {
return rearLeft;
}
public void setRearLeft(int rearLeft) {
this.rearLeft = rearLeft;
}
public int getRearRight() {
return rearRight;
}
public void setRearRight(int rearRight) {
this.rearRight = rearRight;
}
}
vehicleReadingsController.java
package springproject.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import springproject.entity.tires;
import springproject.entity.vehicleReadings;
import springproject.services.vehicleReadingsService;
@RestController
@RequestMapping(value = "vehiclereadings")
public class vehicleReadingsController {
@Autowired
private vehicleReadingsService vehicleReadingsServiceObject;
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public vehicleReadings create(@RequestBody vehicleReadings vehicleReadingsObject){
return vehicleReadingsServiceObject.create(vehicleReadingsObject);
}
}
tiresController.java
package springproject.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import springproject.entity.tires;
import springproject.services.tiresService;
@RestController
@RequestMapping
public class tiresController {
@Autowired
private tiresService tireservice; //tires service object
@RequestMapping(method = RequestMethod.POST)
public tires create(tires tiresObject){
return tireservice.create(tiresObject);
}
}
vehicleReaadingsServiceImpl.java
package springproject.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springproject.entity.vehicleReadings;
import springproject.exceptions.badRequestException;
import springproject.repository.vehicleReadingsRepository;
import java.util.Optional;
@Service
public class vehicleReadingsServiceImpl implements vehicleReadingsService {
@Autowired
private vehicleReadingsRepository vehicleReadingsRepositoryObject;
@Override
public vehicleReadings create(vehicleReadings vehicleReadingsObject) {
Optional<vehicleReadings> existing = vehicleReadingsRepositoryObject.findById(vehicleReadingsObject.getVin());
if(existing.isPresent()){
throw new badRequestException("Record with Vid " + vehicleReadingsObject.getVin() + " already exists.");
}
return vehicleReadingsRepositoryObject.save(vehicleReadingsObject);
}
}
tiresServiceImpl.java
package springproject.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springproject.entity.tires;
import springproject.exceptions.badRequestException;
import springproject.repository.tiresRepository;
import java.util.Optional;
@Service
public class tiresServiceImpl implements tiresService {
@Autowired
private tiresRepository tiresRepositoryObject;
@Override
public tires create(tires tireObject) {
Optional<tires> existing = tiresRepositoryObject.findById(tireObject.getId());
if(existing.isPresent()){
throw new badRequestException("Record with Vid " + tireObject.getId() + " already exists.");
}
return tiresRepositoryObject.save(tireObject);
}
}
vehicleReadingsRepository.java
package springproject.repository;
import org.springframework.data.repository.CrudRepository;
import springproject.entity.vehicleReadings;
public interface vehicleReadingsRepository extends CrudRepository<vehicleReadings, String> {
}
tiresRepository.java
package springproject.repository;
import org.springframework.data.repository.CrudRepository;
import springproject.entity.tires;
public interface tiresRepository extends CrudRepository<tires, String> {
}
Скриншот БД:
введите описание изображения здесь