Search code examples
javaspringhibernatejpa

Delay Update operation until every entity is updated [HIBERNATE]


I currently have the following code:

@Transactional
    public void updateSlots(@NotNull AbstractSlottedLabPatchDTO<?> slottedLabPatchDTO,
            @NotNull AbstractSlottedLab<?> slottedLab) {

        Long duration = slottedLab.getSlottedLabConfig().getDuration();
        List<? extends TimeSlot> timeSlots = slottedLab.getTimeSlots();
        LocalDateTime newStartTime = slottedLabPatchDTO.getSlot().getOpensAt();

        BiFunction<LocalDateTime, Integer, Slot> calculateSlotLambda = (startTime, offset) ->
                new Slot(startTime.plusMinutes(offset * duration), startTime.plusMinutes(offset * duration + duration));

        timeSlots
                .forEach(slot -> slot.setSlot(calculateSlotLambda.apply(newStartTime, slot.getOffsetSequenceNumber())));
    }

In the last statement, I am setting the slot property for each of the individual entities, which causes some problems as I have a unique key constraint, which can be seen below:

@Table(uniqueConstraints = {
        @UniqueConstraint(columnNames = { "lab_id", "opensAt" })
})

In the forEach operation, whilst updating the slot. The opensAt field can overlap as successive slots have not yet been updated. I've tried deleting all the slots and creating new ones, however, I'd rather not do this as other classes actively test for the presence of timeslots.

Thus, I am wondering if there is an operation which can delay the update and execute the update all at once?

Any help is appreciated.


Solution

  • You should try to defer the SQL constraint. You didn't specify which database you are using, but I think most DBs support deferring unique constraints.

    If you can't do that, you'll have to flush changes in order to not run into the unique constraint violation.

    I'd rather not do this as other classes actively test for the presence of timeslots.

    Even if you are using the READ_COMMITTED isolation level, this shouldn't be an issue. At the end of the day, the unique constraint will take care of ensuring consistency.