Task List Repository
With our entities and mappers in place, we now need a way to persist and retrieve TaskList data from our database. In Spring Data JPA, this is done through repository interfaces.
What is a Repository?
Before we create our repository, let's quickly understand what it is and why we need it:
- A repository provides an abstraction over data storage
- It handles the details of database operations
- It allows us to work with our domain objects rather than SQL
- Spring Data JPA will automatically implement the interface for us
Creating the Repository Interface
Let's create a new package com.devtiro.tasks.repositories to hold our repository interfaces. In this package, create a new interface called TaskListRepository:
package com.devtiro.tasks.repositories;
import com.devtiro.tasks.domain.entities.TaskList;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.UUID;
@Repository
public interface TaskListRepository extends JpaRepository<TaskList, UUID> {
}Let's break down what's happening here:
- We annotate the interface with
@Repositoryto mark it as a Spring Data repository - We extend
JpaRepositorywhich provides:- Basic CRUD operations (Create, Read, Update, Delete)
- Paging and sorting support
- Query methods
- The type parameters tell Spring:
TaskListis the entity type this repository managesUUIDis the type of the entity's ID field
What Do We Get?
By extending JpaRepository, our interface automatically gets implementations for:
save(TaskList entity)- Creates or updates a TaskListfindById(UUID id)- Finds a TaskList by its IDfindAll()- Returns all TaskListsdeleteById(UUID id)- Deletes a TaskList by ID- Many more useful methods
The beauty of Spring Data JPA is that we don't need to implement any of these methods - Spring creates the implementations for us at runtime.
Summary
- Created a
TaskListRepositoryinterface for managingTaskListentities - Extended
JpaRepositoryto get built-in CRUD operations - Marked the interface with
@Repositoryfor Spring - Specified
TaskListandUUIDas type parameters - No implementation needed - Spring Data JPA handles that for us