0% found this document useful (0 votes)
15 views5 pages

Repository Pattern - Exception Handling - RestTempla

The document outlines the implementation of the Repository Pattern, Exception Handling, and RestTemplate in Spring Boot. It provides a step-by-step guide for creating a user entity, repository, service, and controller, as well as handling exceptions globally. Additionally, it explains how to configure and use RestTemplate for HTTP requests, emphasizing the importance of these practices for building modular and robust applications.

Uploaded by

goyalgovind1401
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views5 pages

Repository Pattern - Exception Handling - RestTempla

The document outlines the implementation of the Repository Pattern, Exception Handling, and RestTemplate in Spring Boot. It provides a step-by-step guide for creating a user entity, repository, service, and controller, as well as handling exceptions globally. Additionally, it explains how to configure and use RestTemplate for HTTP requests, emphasizing the importance of these practices for building modular and robust applications.

Uploaded by

goyalgovind1401
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Repository Pattern, Exception Handling, and

RestTemplate in Spring Boot

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.

1. Define the Entity

@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;


private String email;

// Getters and setters


}

2. Create the Repository Interface

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {


// Custom query methods can be defined here
Optional<User> findByEmail(String email);
}

3. Service Layer

@Service
public class UserService {
@Autowired
private UserRepository userRepository;

public User createUser(User user) {


return userRepository.save(user);
}

public Optional<User> getUserById(Long id) {


return userRepository.findById(id);
}

public Optional<User> getUserByEmail(String email) {


return userRepository.findByEmail(email);
}

public void deleteUser(Long id) {


userRepository.deleteById(id);
}
}

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.

Global Exception Handling

1. Create Custom Exceptions

public class UserNotFoundException extends RuntimeException {


public UserNotFoundException(String message) {
super(message);
}
}

2. Create a Global Exception Handler

@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_
}
}

3. Throwing Custom Exceptions

@Service
public class UserService {
@Autowired
private UserRepository userRepository;

public User createUser(User user) {


return userRepository.save(user);
}

public Optional<User> getUserById(Long id) {


return userRepository.findById(id).orElseThrow(() -> new UserNotFoundExc
}
public Optional<User> getUserByEmail(String email) {
return userRepository.findByEmail(email);
}

public void deleteUser(Long id) {


userRepository.deleteById(id);
}
}

RestTemplate

RestTemplate is a synchronous client to perform HTTP requests in Spring Boot. It simplifies


communication with HTTP servers and enforces RESTful principles.

Usage

1. Configure RestTemplate Bean

@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}

2. Using RestTemplate

@Service
public class ExternalService {
@Autowired
private RestTemplate restTemplate;

public User getUserFromExternalService(Long id) {


String url = "https://external-service.com/users/" + id;
ResponseEntity<User> response = restTemplate.getForEntity(url, User.clas
return response.getBody();
}

public User createUserInExternalService(User user) {


String url = "https://external-service.com/users";
ResponseEntity<User> response = restTemplate.postForEntity(url, user, Us
return response.getBody();
}
}

Example of GET and POST Requests

1. GET Request

public User getUser(Long id) {


String url = "https://api.example.com/users/" + id;
return restTemplate.getForObject(url, User.class);
}

2. POST Request

public User createUser(User user) {


String url = "https://api.example.com/users";
return restTemplate.postForObject(url, user, User.class);
}

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.

You might also like