Repository Pattern - Exception Handling - RestTempla
Repository Pattern - Exception Handling - RestTempla
Repository Pattern
The Repository Pattern is a design pattern that provides an abstraction over data storage
mechanisms. It allows you to separate the data access logic from the business logic, making your
application more modular and easier to test.
Implementation
In Spring Boot, the Repository Pattern is implemented using Spring Data JPA. Here’s a step-by-step
guide to implementing the Repository Pattern.
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
import org.springframework.data.jpa.repository.JpaRepository;
3. Service Layer
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
4. Controller Layer
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
User createdUser = userService.createUser(user);
return new ResponseEntity<>(createdUser, HttpStatus.CREATED);
}
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
Optional<User> user = userService.getUserById(id);
return user.map(ResponseEntity::ok).orElseGet(() -> new ResponseEntity<>
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
Exception Handling
Handling exceptions properly is crucial for building robust applications. Spring Boot provides
several ways to handle exceptions.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handleUserNotFoundException(UserNotFoundExcept
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGeneralException(Exception ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_
}
}
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
RestTemplate
Usage
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
2. Using RestTemplate
@Service
public class ExternalService {
@Autowired
private RestTemplate restTemplate;
1. GET Request
2. POST Request
Conclusion
Understanding and implementing the Repository Pattern, Exception Handling, and RestTemplate in
Spring Boot can greatly enhance your application’s modularity, robustness, and maintainability. By
following these best practices, you can build scalable and efficient Spring Boot applications.