API REST con Spring Boot | 5 | Completando los métodos del Servicio
New Section
In this section, the speaker discusses the initial steps in constructing a service, including defining the class as a service and creating an implementation of a person repository.
Creating a Service
- Defining the class as a service is done using the annotation
service.
- The next step involves creating an implementation of a person repository.
- Dependency injection is achieved through the constructor or by using the
auto wireannotation.
New Section
This part focuses on dependency injection methods and how Spring manages dependencies within services.
Dependency Injection Methods
- Dependency injection can be done through the constructor by specifying what it will receive.
- Spring automatically obtains dependencies needed by services without explicit calls to constructors.
- The
auto wireannotation serves the same purpose as constructor-based dependency injection.
New Section
The discussion shifts towards making methods transactional to interact with databases effectively.
Making Methods Transactional
- All methods are designated as transactional using annotations.
- Annotations like
@Transactionalhandle transactions, eliminating manual transaction management.
- Exception handling within each method ensures proper error management during database interactions.
New Section
This segment delves into implementing specific methods within the service, starting with 'find all'.
Implementing 'Find All' Method
- Declaring a list of persons from the database using
personRepository.findAll().
- Returning entities obtained from the database query.
- Handling exceptions by throwing new exceptions with appropriate messages for error tracking.
New Section
Continuing with method implementations, focusing on 'find by id' and exception handling strategies.
Implementing 'Find By Id'
- Utilizing an optional type to handle cases where entities may not exist in the database.
- Returning either an entity if found or throwing an exception if not found.
New Section
Concluding method implementations with 'delete', checking for entity existence before deletion.
Implementing 'Delete'
- Verifying entity existence based on provided parameters before deletion.