gpt4 book ai didi

java - 关系未设置为一对多关系

转载 作者:行者123 更新时间:2023-11-30 10:20:19 24 4
gpt4 key购买 nike

我使用 Spring Boot 2,Spring Data 和 Hibernate 实现。使用的数据库是Postgres

我尝试用它的子 CarComponentOccurrences 保存 CarServices:

@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 已保存,但在数据库中 CarComponentsCarService 为空。

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 中:

  • cascade = CascadeType.PERSIST -> PERSIST, MERGE

CarComponentOccurrences 中:

  • @ManyToOne 私有(private) CarComponents carComponent; -> @ManyToOne(cascade=CascadeType.PERSIST)

如果有帮助,请告诉我。

关于java - 关系未设置为一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48264228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com