关系未设置为一对多关系

时间:2018-01-15 13:43:31

标签: java hibernate jpa spring-data-jpa

我使用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已保存,但在db 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=?

2 个答案:

答案 0 :(得分:1)

尝试:

CarServices

  • cascade = CascadeType.PERSIST - &gt; PERSIST,MERGE

CarComponentOccurrences

  • @ManyToOne私人CarComponents carComponent; - &GT; @ManyToOne(级联= CascadeType.PERSIST)

如果有帮助,请告诉我。

答案 1 :(得分:0)

如果db中的列名是car_component_idcar_service_id,那么您应该使用@JoinColumn注释来覆盖持久性提供程序的默认值,这是默认的:{{1 }和carcomponent_id(如果这些引用实体的主键分别命名为carservice_id)。

来自JoinColumn的参考:

  

默认值(仅在使用单个连接列时适用):   连接以下内容:引用的名称   关系属性或引用实体的字段或可嵌入的   类; id;引用的主键列的名称。