Service Layer
Now we'll implement listing tasks. The good news is that there are no new classes to create!
However, we do need to update the TaskService interface.
Update the Task Service Interface
The TaskService interface already has the createTask method we added earlier.
We're now going to add a second one to define listing tasks.
Let's add the listTasks method to the TaskService interface:
/**
* Lists all tasks.
*
* @return A list of all tasks.
*/
List<Task> listTasks();This new method doesn't require any arguments. It simply returns a list of all task entities in the database.
Note
Returning all entities in the database may not always be ideal. If there are a lot of entities then we could see some serious performance problems! Pagination is one solution to this challenge, but we use a list here to keep this build approachable.
Now let's implement the new method.
Implement the List Tasks Method
Let's head over to TaskServiceImpl and implement our new listTasks method:
@Override
public List<Task> listTasks() {
return taskRepository.findAll(Sort.by(Direction.ASC, "created"));
}We're relying on the task repository to do a lot of the hard work in this method!
Although we could simply call findAll without arguments to get a list of tasks,
we're asking for the results to be sorted oldest to newest.
That's the service layer complete, let's move on to the list tasks endpoint in the presentation layer.
Summary
- Added the
listTasksmethod to theTaskServiceinterface. - Implemented the
listTasksmethod.