Hibernate OneToMany bidirectional merge

50 views Asked by At

I have a simple OneToMany relationship between two entities like this:

public class ScheduleInfo {
        ...

    @OneToMany(mappedBy = "scheduleInfo", fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
    private List<PlannedBusinessProcedure> plannedBusinessProcedures = new ArrayList<>();


    public void addPLannedBusinessProcedure(PlannedBusinessProcedure plannedBp) {
        plannedBusinessProcedures.add(plannedBp);
        plannedBp.setScheduleInfo(this);
    }
}
public class PlannedBusinessProcedure {
        ...

    @ManyToOne(fetch = FetchType.LAZY, optional = true)
    @JoinColumns({ 
    @JoinColumn(name = "SCHEDULE_INFO_ID", nullable = false, referencedColumnName="ID"), 
    @JoinColumn(name = "SCHEDULE_INFO_VERSION", nullable = false, referencedColumnName = "VERSION") 
    })
    private ScheduleInfo scheduleInfo;

}

I would like to UPDATE the entity ScheduleInfo adding new PLannedBusinessProcedures and to achieve this I have an helper method which is used to synchronize both sides of the bidirectional association. I would do something like this :

public void updateScheduleInfo(ScheduleInfo resource) {
    List<PlannedBusinessProcedure> plannedBpNotExecutedYet = ... ; // list of 5 plannedBusinessProcedures
    plannedBpNotExecutedYet.forEach(resource::addPLannedBusinessProcedure);
    entityManager.merge(resource);
}

If I call the update method it takes too long time to execute, actually it never ends and I can't figure out why. Does anyone have idea why this happen? Thanks.

0

There are 0 answers