The UserDao
interface extends JpaRepository<User, Long>
to provide data access operations for the User
entity.
Key Methods:
public interface UserDao extends JpaRepository<User, Long> {
// User sign-in: Find user by email and password
Optional<User> findByEmailAndPassword(String email, String password);
// List users born between a date range with a specific role, sorted by subscription amount
List<User> findByDobBetweenAndUserRoleOrderBySubscriptionAmount(LocalDate begin, LocalDate end, UserRole role);
// User sign-up: Inherited from CrudRepository
// save(entity) - Persists or updates the entity
// Sorting and limiting queries
Optional<User> findFirstByOrderByLastnameAsc(); // Find first user sorted by lastname (ascending)
Optional<User> findTopByOrderByAgeDesc(); // Find top user sorted by age (descending)
List<User> findTop10ByLastnameOrderBySubscriptionAmount(String lastname); // Find top 10 users with given lastname, sorted by subscription amount
}
final
fields.@AllArgsConstructor
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
// Controller methods
}
@AllArgsConstructor
(from Lombok) generates a constructor to inject UserService
.Instead of repetitive try-catch blocks in controller methods, implement centralized exception handling using @RestControllerAdvice
to handle exceptions consistently across all endpoints.
Why?
Example:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error ->
errors.put(error.getField(), error.getDefaultMessage())
);
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ApiResponse> handleResourceNotFoundException(ResourceNotFoundException ex) {
ApiResponse response = new ApiResponse(ex.getMessage(), LocalDateTime.now());
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
}