Java 未在一对多关系中设置的关系
我使用Spring Boot 2,Spring数据与Hibernate实现。 使用的数据库是Postgres 我尝试将Java 未在一对多关系中设置的关系,java,hibernate,jpa,spring-data-jpa,Java,Hibernate,Jpa,Spring Data Jpa,我使用Spring Boot 2,Spring数据与Hibernate实现。 使用的数据库是Postgres 我尝试将CarServices与其子项carcomponentexecutions: @Entity public class CarServices{ @OneToMany(mappedBy = "carService", cascade = CascadeType.PERSIST) private List<CarComponentOccurrences>
CarServices
与其子项carcomponentexecutions
:
@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;
}
编辑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=?
如果数据库中的列名是
car\u component\u id
和car\u service\u id
,则应使用@JoinColumn
注释来覆盖持久性提供程序的默认值,该持久性提供程序应为:carcomponent\u id
和carservice\u id
(如果这些引用实体的主键分别命名为id
)
参考资料来源:
默认值(仅在使用单个联接列时适用):
下列内容的串联:引用的名称
引用实体或可嵌入实体的关系属性或字段
类;引用的主键列的名称
尝试:
在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;
}
- cascade=CascadeType.PERSIST->PERSIST,MERGE
carcomponentoccurrencess
中:
@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;
}
- @ManyToOne私有CarComponents carComponent;->@ManyToOne(cascade=CascadeType.PERSIST)
让我知道这是否有帮助。尝试添加设置和保存实体的整个方法OK我更新了帖子所以在会话或EntityManager等上调用了实际的保存/持久化在哪里。我添加了保存代码我使用spring security save…所以只有外键没有设置?CarService是否已执行?完成了此修改但没有任何变化,这是同一个问题。原因如下:您持久化了一个CarServices。现在,为了让Hibernate级联任何持久化操作,必须使用一个不间断的对象链进行注释,即CarServices->CarComponentInstances->CarComponents。缺少@ManyTone上的级联会导致CarComponents无法持久化。根据我的经验,Persist-chain和Persist-only通常不适用于集合,尽管很奇怪CarService在这种情况下没有得到持久化。