Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

hibernate - Why save() is necessary in Spring Data?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'd say that this text you cite is just a good practice - it enhances the code readability / maintainability, i.e. remember that if you detach an entity within a @Transactional method, this entity won't be persisted. And explicitly stating the persisting of an entity is pretty much self-explanatory for the developer (or causes exceptions in case of mentioned detachment, which is self explanqtory as well).

I'd say that this consistency you were asking about means exactly that, at least for me. Being consistent meaning explicitly implementing a method that would be invoked anyway ("under the hood", which most often leads to bugs).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...