Question

I'm wondering what to expect when I use cascade = CascadeType.ALL as such,

@OneToMany(
         mappedBy = "employeeProfile",
         cascade = CascadeType.ALL,
         orphanRemoval = true)
private List<ProfileEffortAllocation> effortAllocations;

public List<ProfileEffortAllocation> getEffortAllocations() {
    if (effortAllocations == null) {
        effortAllocations = new ArrayList<>();
    }
    return effortAllocations;
}

public void setEffortAllocations(List<ProfileEffortAllocation> effortAllocations) {
    this.effortAllocations = effortAllocations;
}

I'm finding when I add a new effortAllocation and attempt to save object, but have a validation failure preventing my code from ever reaching session.saveOrUpdate(parentObj), I'm still getting a pk rather than null as if persist is being called on the child OneToMany. Should my parent object call session.saveOrUpdate(parentObj); before I ever see a pk from effortAllocation?

I'd like to point out that the parent object is an existing object and has been loaded from the database with a pk prior to adding a new child record.

Was it helpful?

Solution

When you use CascadeType.ALL, whenever you do any operation on the parent all those operations would also get cascaded to the child.

Yes you should call saveOrUpdate(parent)

In your case as the parent objects are already existing. You could load the existing parent and create a new child and attach the child to parent and when you call saveOrUpdate(parent), it should update the parent and create all those child and relate it to that parent.

Yes it is generating a id for child, because it is trying to create a child due to cascade all and you could have configured it to generate id in @Id.

Enable sql logs using hibernate.show_sql to understand better whats happening.

I assume you would have a @JoinColumn in your child which would map to the parent primary key.

OTHER TIPS

The cause of this issue was do to a lookup query triggering a flush prior to returning it's results. The solution was to set this.session.setFlushMode(FlushMode.COMMIT);

Hibernate tries to ensure that database conents is up-to-date before making any queries.

https://forum.hibernate.org/viewtopic.php?p=2316849

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top