In Spring Data JPA documentation, under Transactionality section there is an example about using a facade to define transactions for multiple repository calls:
@Service
class UserManagementImpl implements UserManagement {
private final UserRepository userRepository;
private final RoleRepository roleRepository;
@Autowired
public UserManagementImpl(UserRepository userRepository, RoleRepository roleRepository) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
}
@Transactional
public void addRoleToAllUsers(String roleName) {
Role role = roleRepository.findByName(roleName);
for (User user : userRepository.findAll()) {
user.addRole(role);
userRepository.save(user);
}
}
}
And there is a note that the call to save
is not strictly necessary from a JPA point of view, but should still be there in order to stay consistent to the repository abstraction offered by Spring Data.
I understand that because of the transaction everything at the end of it will be persisted to the database even without the save()
call. But I don't understand why it should still be there and what does it mean to stay consistent to the repository abstraction offered by Spring Data.
I see .save()
as a redundant call.
question from:
https://stackoverflow.com/questions/65871706/why-save-is-necessary-in-spring-data 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…