From aa122113ade36f02dc8fdbebdf1232b5c4b8742c Mon Sep 17 00:00:00 2001 From: Kamal Wickramanayake Date: Fri, 3 Jul 2026 19:02:36 +0530 Subject: Microservice sample projects --- .../resourceserver/security/UserService.java | 47 ++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 microservices/03-resource-server/src/main/java/com/example/resourceserver/security/UserService.java (limited to 'microservices/03-resource-server/src/main/java/com/example/resourceserver/security/UserService.java') diff --git a/microservices/03-resource-server/src/main/java/com/example/resourceserver/security/UserService.java b/microservices/03-resource-server/src/main/java/com/example/resourceserver/security/UserService.java new file mode 100644 index 0000000..1f6ddac --- /dev/null +++ b/microservices/03-resource-server/src/main/java/com/example/resourceserver/security/UserService.java @@ -0,0 +1,47 @@ +package com.example.resourceserver.security; + +import java.util.List; +import java.util.Optional; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Sort; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; + +import jakarta.transaction.Transactional; + +@Service +public class UserService { + + @Autowired + private UserRepository userRepository; + + public Optional findByUsername(String username) { + return userRepository.findByUsername(username); + } + + public Optional findById(Long id) { + return userRepository.findById(id); + } + + public List findAll() { + return userRepository.findAll(Sort.by(Sort.Direction.ASC, "username")); + } + + @PreAuthorize("hasRole('ADMIN')") + @Transactional + public void updateUser(Long id, String description) { + // Do whatever the work needed. + // ... + + Optional userOpt = userRepository.findById(id); + + User user = userOpt.get(); + + user.setDescription(description); + + // NO userRepository.save(user) IS ACTUALLY REQUIRED HERE since the method + // has been annotated with @Transactional! + // Transaction commits -> Hibernate issues the SQL UPDATE. + } +} -- cgit v1.2.3