dev123
dev123

Reputation: 475

Save, delete and update within a single transaction in Spring Data JPA

I have a following method:

@Transactional
public void saveUpdateAndDelete(Entity newEntity, Entity updatedEntity, long deleteEntityId) {
  entityRepository.save(newEntity);
  entityRepository.findById(updatedEntity.getId())
    .ifPresent(e -> e.setName(updatedEntity.getName));
  entityRepository.deleteById(deleteEntityId);
}

How can I assure that all statements in saveUpdateAndDelete method will be executed within a single transaction?

Edit: the question purpose is to solve some implementation problem, not about how @Transactional is handled by Spring by creating proxy classes, which is explained here: Spring - @Transactional - What happens in background?.

Upvotes: 1

Views: 5609

Answers (1)

Julian
Julian

Reputation: 401

As @JB Nizet already states in his comment, this is the exact purpose of @Transactional, so it will all be in one transaction. But ensure that you call the method from another bean and not from another method in the same class! As you already indicated, transactional doesn't work then.

Upvotes: 1

Related Questions