我使用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
中,设置了CarComponents
和CarService
。
编辑:
在我的服务层
@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=?
答案 0 :(得分:1)
尝试:
在CarServices
:
在CarComponentOccurrences
:
如果有帮助,请告诉我。
答案 1 :(得分:0)
如果db中的列名是car_component_id
和car_service_id
,那么您应该使用@JoinColumn
注释来覆盖持久性提供程序的默认值,这是默认的:{{1 }和carcomponent_id
(如果这些引用实体的主键分别命名为carservice_id
)。
来自JoinColumn的参考:
默认值(仅在使用单个连接列时适用): 连接以下内容:引用的名称 关系属性或引用实体的字段或可嵌入的 类;
id
;引用的主键列的名称。