For Example:
@Override
@Transactional(readOnly = true)
public List<PostResponse> getPostsByUsername(String username) {
final User user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User does not exist"));
return postRepository.findAllByUser(user)
.stream()
.map(postMapper::mapToDto)
.collect(Collectors.toList());
}
I was hoping someone could explain this to me.
While its not mandatory to mark the methods with this, the transactional annotation will make it easy to handle transactions (a cross cutting concern) at multiple places without rewriting the code everytime in your method. It takes care of entity manager creation, binding it to the current thread, gets a new connection and binds to the thread etc, and any customization you need around this, you can write it just once and use it anywhere you need. Please refer: https://dzone.com/articles/how-does-spring-transactional to get a better understanding.