I want to delete all records with some lineId to save another records with the same lineId(as refresh) but after deleting I can't save anything. There isn't any error, but I don't have my record in database.
When I don't have ma deleting code everything saves correctly.
public void deleteAndSaveEntities(List<Entity> entities, Long lineId){
deleteEntities(lineId);
saveEntities(entities);
}
private void deleteEntities(Long lineId) {
List<Entity> entitiesToDelete = entityRepository.findAllByLineId(lineId);
entityRepository.deleteAll(entitiesToDelete);
}
private void saveEntities(List<Entity> entities) {
entityRepository.saveAll(entities);
}
CodePudding user response:
Actually you want to update the entries that has the lineId
. Try it as:
- First fetch by find..().
- Make related changes on that entries
- Then save them.
CodePudding user response:
As thomas mentioned, hibernate reorders the queries within the transaction for performance reasons and executes the delete after the update.
I would commit the transaction between these two operations. Add a @Transactional over deleteEntities and saveEntities. But be aware that @Transactional does not work when invoked with in the same object. You must inject the Service into itself and then call the methods on the self reference