Learn how to call the default Create, Read, Update, and Delete methods of a Spring Data JPA CrudRepository interface.
- [Instructor] So let's inject the repositories into services. First of all, I'm going to create a service package. Services package. And create tour package service. This will be a service annotation for the service stereotype. And we will inject the tour package repository.
And I will let the IDE generate my constructor, and auto-wire it. Now let's create some public methods. Let's create one to create a tour package. Tour package. And the attributes of a tour package are code and name.
So before I create a tour package I want to make sure that there doesn't exist one already in the database. So if there doesn't exist one of those already I'm going to create one with the tour package repository. If one does exist already then we will return a NULL.
Now let's create a method to look up all of the tour packages in the database. And we're going to invoke the find all method on tour package repository. And finally, let's find out the total number of tour packages in the database. Invoke the count method.
Okay save that and now let's create a tour service. Which is also a service, and we're going to inject not just the tour repository but the tour package repository into this service. And let's generate the constructor for that, and auto-wire it.
Now let's create a method to create a brand new tour, and we're going to pass in all of the attributes of a tour. Now before we create a tour we need to get the tour package entity from the database. So, we're going to look that up.
So, finding the tour package by the code If we find it that's good. If we don't find it that's bad, and we need to throw an exception. So if the tour package lookup results in a NULL we will throw a runtime exception, and give the message, "Tour package does not exist". If we do find the tour package then we are going to create a new tour object, and save it to the database, and return that entity's reference.
So, we're going to instantiate a new tour, and pass in all the attributes of a tour. Okay, so now we have a method to create a tour, and let's create a public method to look up all the tours, and get the total number of tours. So now that we have these services, let's build it and run it.
So I'm going to go to the command line, and type maven install. And it builds and now we're ready to run it. And it runs and it will inject those repositories into the services.
- Setting up the project
- Building, deploying, and launch the microservice
- Declaring Spring Data JPA repository interfaces
- Invoking repositories
- Using Spring Data query methods
- Exposing RESTful APIs with Spring Data REST
- Using the /search resource to invoke query methods
- Paging and sorting
- Declaring a new REST controller
- Creating HTTP methods for creating, reading, updating and deleting persistent data.