CarComponentOccurrences

CarComponentOccurrences

我将Spring Boot 2和Spring Data与Hibernate实现结合使用。
使用的数据库是Postgres

我尝试将CarServices与它的子CarComponentOccurrences保存在一起:

@Entity
public class CarServices{

    @OneToMany(mappedBy = "carService", cascade = CascadeType.PERSIST)
    private List<CarComponentOccurrences> carComponentOccurrences;

}


@Entity
public class CarComponentOccurrences {
    ...
    @ManyToOne
    private CarComponents carComponent;

    @ManyToOne
    private CarServices carService;

}


CarComponentOccurrences已保存,但在数据库CarComponents中且CarService为空。

CarComponentOccurrences中,设置了CarComponentsCarService

编辑:

在我的服务层

@Autowired
private CarServicesRepository repository;

public void save(){
    CarServices cs = new CarServices();
    cs.setName("name");

    List<CarComponentOccurrences> carComponentOccurrences = new ArrayList<>();

    CarComponentOccurrences cco = new CarComponentOccurrences();
    Optional<CarComponents> optCarComponents =carComponentsRepository.findById(1);
    if (optCarComponents.isPresent()) {
        cco.setCarComponentOccurrences(optCarComponents.get());
    }

    cco.CarServices(cs);

    carComponentOccurrences.add(cco);
    cs.setCarComponentOccurrences(carComponentOccurrences);

    repository.save(cs);
}


编辑2

CREATE TABLE car_component_occurrences
(
  id integer NOT NULL,
  ...
  car_component_id integer,
  car_service_id integer,
  CONSTRAINT car_component_occurrences_pkey PRIMARY KEY (id),
  CONSTRAINT fka4fmpytg0s9a94377pdw5ssib FOREIGN KEY (car_service_id)
      REFERENCES car_services (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fko85tjs5s6f1o9u7kkk152d147 FOREIGN KEY (car_component_id)
      REFERENCES car_components (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)


编辑3

Hibernate:
    select
        nextval ('public.car_component_occurrences_id_seq')
Hibernate:
    insert
    into
        public.car_component_occurrences
        ( car_component_id, car_service_id, name, id)
    values
        (?, ?, ?, ?)
Hibernate:
    update
        public.car_services
    set
        name=?,
    where
        id=?

最佳答案

尝试:

CarServices中:


级联= CascadeType.PERSIST-> PERSIST,MERGE


CarComponentOccurrences中:


@ManyToOne私人CarComponents carComponent; -> @ManyToOne(cascade = CascadeType.PERSIST)


让我知道是否有帮助。

07-27 13:28