Task Repository
Now that we have our Task entity defined, we need a way to persist and retrieve tasks from our database.
Creating the Repository Interface
First, let's create a new interface called TaskRepository:
package com.devtiro.tasks.repositories;
import com.devtiro.tasks.domain.entities.Task;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Repository
public interface TaskRepository extends JpaRepository<Task, UUID> {
List<Task> findByTaskListId(UUID taskListId);
Optional<Task> findByTaskListIdAndId(UUID taskListId, UUID id);
}Let's break down what we've done here:
1. Repository Annotation
@Repositorymarks this as a Spring repository component- Spring will automatically create an implementation of this interface
2. JpaRepository Extension
- We extend
JpaRepository<Task, UUID>- First type parameter
Taskis the entity type - Second type parameter
UUIDis the type of the entity's ID
- First type parameter
- This gives us many built-in methods for free:
save(Task entity)findById(UUID id)findAll()delete(Task entity)- And many more
3. Custom Query Methods
We have two custom query methods that leverage Spring Data JPA's method name query generation:
findByTaskListId
- Returns all tasks belonging to a specific task list
- Takes a
taskListIdparameter - Returns a
List<Task>containing all matching tasks - Useful for getting all tasks in a specific list
findByTaskListIdAndId
- Finds a specific task within a specific task list
- Takes both
taskListIdandidparameters - Returns an
Optional<Task>to handle cases where no matching task is found - Ensures tasks can only be accessed within their proper task list context
Using Method Name Query Generation
Spring Data JPA's method name query generation allows us to create custom queries just by following naming conventions. Let's break down how it works:
For findByTaskListId:
find- indicates this is a select queryBy- starts the criteria definitionTaskListId- look at the taskList relationship and match its id
Spring generates a query like:
SELECT t FROM Task t WHERE t.taskList.id = ?1
For findByTaskListIdAndId:
find- indicates this is a select queryBy- starts the criteria definitionTaskListId- look at the taskList relationship and match its idAnd- combine with another conditionId- match the task's id
Spring generates a query like:
SELECT t FROM Task t WHERE t.taskList.id = ?1 AND t.id = ?2
Summary
- Created the
TaskRepositoryinterface extendingJpaRepository - Got basic CRUD operations for free from
JpaRepository - Added two custom query methods using Spring Data JPA's method name convention
- Leveraged Spring's automatic query generation from method names