简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM