Skip to content

Instantly share code, notes, and snippets.

@dantonyuk
Last active July 15, 2020 19:34
Show Gist options
  • Save dantonyuk/a6255d171743a8608582d8e58a04cf1e to your computer and use it in GitHub Desktop.
Save dantonyuk/a6255d171743a8608582d8e58a04cf1e to your computer and use it in GitHub Desktop.

Call Transactional Method in the Same Class

Given a repository and a service

// UserRepository.java
public interface UserRepository {
    void createUser(User user);
    void persistUser(User user);
}

// UserRepositoryImpl.java
@Repository
public class UserRepositoryImpl implements UserRepository {

    @Override
    public void createUser(User user) {
        validateUser(user);
        persistUser(user);
    }

    @Override
    @Transactional
    public void persistUser(User user) {
        // actually persist the user
    }

    private void validateUser(User user) {
        // do some validation
    }
}

// UserService.java
@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    // ...
    // somewhere in the UserService methods
    userRepository.createUser(user);
    // ...
}

will the call userRepository.createUser(user) in the UserService create a transaction?

Follow-up

  • Why?
  • How to fix?
  • Will your fix work if we make persistUser private? Why?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment