简体   繁体   中英

Persisting/saving a JPA entity's relationships before that entity itself

I have a @OneToMany JPA association with an instance of Curriculum having several instances of WorkExperience .

The Curriculum JPA entity:

@Entity
public class Curriculum {
    ...
    @OneToMany
    private Set<WorkExperience> workExperiences;
    ...

The WorkExperience JPA entity:

@Entity
public class WorkExperience {
...

I originally wanted to persist the Curriculum together with its WorkExperiences in one entityManager call of the persist method.

However, given how I designed the flow of actions of the web UI, I am now wondering whether another scenario might not be possible ie to:

  • persist the WorkExperiences to db first and then when the user has filled in the main Curriculum entity details, to :

  • set the existing WorkExperience instances (already in db) to the Curriculum instance (not in db yet) and

  • persist the whole object graph: Curriculum with its WorkExperiences.

Does that make sense? I thought of several cons, eg what happens if the user chooses not to persist the Curriculum instance? How do I clean up the dangling lines in the WorkExperience table?

Are there alternatives or better patterns? For instance would that be a good idea to pre-save the curriculum instance before the user validates the form?

I would define a cascade on the Curriculum , since WorkExperience seems to be a dependent entity.

Then work with new/detached entities in the UI/Controllers until the user decides to submit the (last) form. Then persist the Curriculum and the related WorkExperience entities will be persisted as well during the same transaction commit.

@OneToMany(cascade=CascadeType.ALL)
private Set<WorkExperience> workExperiences;

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