简体   繁体   中英

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? .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM