Paste after deleting the same transaction in Spring Data JPA

Using Spring Data JPA I have the following thread inside a single transaction (REQUIRES_NEW):

  • Delete a set of custom forecasts using this JPA Spring data repository method.

    @Query(value = "DELETE FROM TRespuestaUsuarioPrediccion resp WHERE resp.idEvento.id = :eventId AND resp.idUsuario.id = :userId") @Modifying void deleteUserPredictions(@Param("userId") int userId, @Param("eventId") int eventId); 
  • Insert new custom forecasts and save the main object (event).

     eventRepository.save(event); 

When this service ends, the commit is performed by AOP, but only works in the first attemp ... not in the following ...

How can I manage this situation without repeating the records of event events and updating each of them internally?

UPDATE

I tried with this and it does not work (the adapter inserts the objects that I delete earlier):

 @Transactional(propagation=Propagation.REQUIRES_NEW, rollbackFor=PlayTheGuruException.class) private void updateUserPredictions(final TUsuario user, final TEvento event, final SubmitParticipationRequestDTO eventParticipationRequestDTO) { eventRepository.deleteUserPredictions(user.getId(), event.getId()); EventAdapter.predictionParticipationDto2Model(user, event, eventParticipationRequestDTO); eventRepository.save(event); } 
+4
source share
2 answers

Sleep mode has reordered the commands. It works in the following order: Perform all updates to the SQL cache and the second level in a special order so that the foreign key restrictions cannot be violated:

  1. Inserts, in the order they were performed 2. Updates 3. Deletion of collection elements 4. Insertion of collection elements 5. Deletes, in the order they were performed 

And that is exactly so. When flushing, Hibernate performs all insertions before delete operations. Possible variant:
1. To call entityManager.flush () explicitly immediately after deletion. OR 2. If possible, update existing rows and create a ToBeDeleted List. This will ensure that existing records are updated with new values ​​and that completely new records are retained.

+1
source

You can solve this problem by introducing a new @Transactional method that performs both tasks.

 @Transactional public void deleteAndSave(/*...*/) { deleteUserPredictions(/*...*/); eventRepository.save(event); } 
0
source

Source: https://habr.com/ru/post/1502636/


All Articles