[英]Jpa OneToMany relationship handling relation during saving automatically
Is it possible for Hibernate / JPA to fill in the reference itself or do I first have to persist entity A so that I receive an ID that I can set to entity B? Hibernate / JPA 是否可以填写引用本身,还是我首先必须保留实体 A 以便我收到一个可以设置为实体 B 的 ID?
I have the following entities for this example:对于此示例,我有以下实体:
@Entity
class A(uuid: UUID? = null,
@OneToMany(
mappedBy = "aUUID",
cascade = [CascadeType.ALL],
fetch = FetchType.LAZY,
orphanRemoval = true)
val b: List<B>
) : BaseEntity(uuid)
@Entity
class B(uuid: UUID? = null,
@Column(nullable = false) val aUUID: UUID,
) : BaseEntity(uuid)
B is referencing with a foreign key to A B 使用 A 的外键引用
You can persist both entities together (not exactly for this case but same logic):您可以将两个实体保存在一起(不完全适用于这种情况,但逻辑相同):
A a = new A();
a.setBList(new ArrayList());
B b = new B();
a.getBList().add(b);
yourJpaRepository.save(a); // will persist both entities and add reference
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.