Now that we have a general idea of how to set up our entity classes and repositories, let’s take a deeper dive into how repositories are used to perform CRUD operations on a database.
17.3.1. CRUD Operations¶
Previously, we learned that we can create a repository to fetch rows of a table in a database.
To do so, we need to create a corresponding controller.
When creating our controller, we add a variable of the repository type that has the annotation
Next, we will learn how to use some of the more common
CrudRepository methods, such as
findById(ID id), and
17.3.2. Using Persistence in a Controller - Video¶
The following video explains how we can add a controller to manage persistence in our
The accompanying text is a quick rundown of what happens in the video. To get started, create a branch off of your persistent-model branch.
The starter code for this video is found at the persistent-model branch of the
The final code presented in this video is found on the persistent-controller branch. As always, code along to the
videos on your own
18.104.22.168. Using Persistence in a Controller - Text¶
EventController, we can add a variable of type
EventRepository and give it an
For events, we want to be able to display all of the events in our database as well as add and delete events.
When displaying the events in our database, we write a method,
We want to use
displayAllEvents to display a table that contains all of our events.
We did something similar to this before, but we used a list or iterable containing all of the objects we wanted to display.
Since we have set up ORM between the MySQL database and our MVC application, we need to use the methods from
CrudRepository to get all of the instances of the
We can use the
findAll() method to return an iterable containing all of the events in our database.
As you write the methods necessary for
EventController, you might notice that this controller doesn’t look too different from other controllers we previously created.
Now we need to use the methods in
CrudRepository to fetch the necessary information or update the correct table.
17.3.3. Check Your Understanding¶
True or false: We add different methods directly to our repository.