Before continuing on this tutorial, ensure you have reviewed/read part 1 before moving forward: Setting your own spring boot server via JDBC part 1 | by Michael Tong | Dec, 2020 | Medium
In part 2, we will talk about how to set up endpoints to perform crud operations, as well as the structure of the rest of the application.
To have some context as to how the application will be implemented, let’s take a look at the following image:
We have the controller, which listens to client requests via api endpoints. Depending on what the requests are looking for, we call the respective service which handles the business logic.
Often times this can mean calling another 3rd party service or sanitizing data coming from the controller.
For example, if we are building a backend server that handles/manages aws ec2 services, we would need to make a call to aws service to either create/modify/delete exist ec2 instances, and update our database to reflect the true status of the instances.
If that was a bit hard to understand, let’s use a shopping cart application as an example. We can have a controller that takes in endpoints to purchase items. From there, we receive the request and calls a shoppingCart service, which checks if the data was received from the request is valid. If it is valid, the service interacts with the dao layer, which updates the database by inserting a new entry for a new transaction.
Afterward, you can return either the record of the transaction or a customized request with the 200 code from the dao layer. This will be passed back to the service layer and then to the controller layer, in which the controller will give the response back to the client.
After all this talking, let’s now focus on the implementation on the remaining pieces in this project.
Let’s go to the directory under src/main/java/com.example.demo and create four new packages:
We are going to focus one layer at a time. So let’s focus on the controller now.
Step 1: Create model package and add a DemoController.java
For the remaining of this tutorial, we will be working with one entity, and we are going to call it a cluster.
This cluster will contain a name and an id:
This will be used as an entity that we will use to store database data to. Later on, I will be providing a script to create a cluster with name and id.
@JsonInclude(JsonInclude.Include.NON_NULL) is an annotation used to excluding any entities that are null, meaning when we map database data back to controller, we will only be giving non-null values. However, do note that this does not exclude the entity objects themselves from having null values, if the entity objects are not null.
Great, now we have created our first entity. However, when we retrieve data from the database it does not know how to get mapped to our entity objects automatically. To do that, we need to create row mapper class called ClusterMapper.java:
Over here, we take the resultset that we get via the jdbc library and get the row name and id property and create a cluster out of it.
That’s it! Over here, the string that we pass in to get the specific property from the database has to match exactly, meaning the database properties need to be spelled “name” and “id” exactly.
The clusterMapper will be used later on when we are going to implement the dao layer.
Step 2: set up api endpoints in the controller layer
This is where we decide which endpoints the application will open, and what endpoints client calls can hit to perform crud operations.
To keep it simple, we will have endpoints to create, delete, update, and get clusters:
To establish a working controller, we need to use annotation @RestController to let the spring boot application know this is one of the controller that will be listen to endpoints.
After that, we need to specify @RequestMapping which specifies how all the endpoints in this controller will begin with. For example, if we are calling an api to get all the clusters, we will be making a call to localhost:8080/v1/clusters to get the data(because the server will be running on 8080 locally).
Inside the controller, we also have a clusterService we are autowiring to. Wait a minute, what does autowiring mean?
Autowiring is a part of spring’s ability to inject dependencies. In this case, we will be creating a service and serviceimpl.java, where the service will be an interface. Normally, we would need to instantiate the service before using it. In spring boot, all we have to do is autowire the service so spring boot knows exactly where to look for the service implementation.
Over here, we have createClusters, retrieveClusters, deleteClusters, and updateCluster.
With createClusters, we are expecting a list or an array of objects with cluster id and name. We then call the service to create these clusters and return a response entity with the data that was created and also a httpstatus of 200, indicating a successful creation.
With retrieveClusters, it is a relatively straightforward call as we just have to return the list of clusters from the service.
With deleteClusters, we expect to receive a list of ids, which will be used to delete a list of clusters in the database.
With updateCluster, we take a new cluster with an id that matches to an existing id in the database, and we use clusterService to interact with the database to update that entry. If the update is successful, then we return a responseEntity with the updated cluster and a httpstatus code of 200.
Step 3: Establishing the service layer to interact with our dao layer
Now that we finished talking about the controller works, let’s take a look at our service layer. First we need to create a clusterService.java under src/main/java/com.example.demo/service package:
Afterward, we need to create a clusterServiceImpl.java that will be implementing all these existing functions:
Remember in the ClusterController.java file we have an autowired ClusterService? When we autowire that service, it actually specifically look for this file because it knows that this is the only file that implements the ClusterService itself.
In this file, we have to specify @Service indicating to the application this is one of the services we are using for this application. We also have to autowire to a dao class itself, which will be used to interact with the database directly.
Step 4: Establishing the dao layer and understand how it interacts with the database
Dao, also known as Data Access Object, is where we provide some sort of mechanism to interact with the database on a lower level, away from the business logic.
Let’s take a look at how the interface looks like:
And now let’s look at the dao implementation of this class:
Over here, we declared ClusterDaoImpl to have @Repository. This tells the spring application that this file will be used to interact with the database. For createClusters, we iterate through each newCluster and we run a postgres query to insert a new entry into the database.
Likewise, for the other query calls, we can also delete or edit clusters just like we do if we run the queries ourselves in pgAdmin, where we can modify the database.
With everything established now, you can go to demoApplication under src/main/java/com.example.demo/demoApplication.java and go to line 9 and click on the play icon to run:
And your server should be running!
To test your endpoints, you can download postman from here: Download Postman | Try Postman for Free.
Afterward, open the postman app and click on the collection tab:
Now add a new api call with the following url: https://localhost/8080/v1/clusters. To the left of the url, you can set POST as your api type, since you will be creating a cluster. Afterward, you can click “save as” and you will be prompted to this page:
Call it “Create Cluster” and select Clusters as the collection to save to.
Click on the “Body” tab and select the “raw” radio button. Next to the “GraphQL” option, select “JSON” as the type of data to send. In the textbox below, you can send a sample JSON like this:
After that, you should get a successful 200 httpStatus Ok response with this json as the response you receive from the server!
You can also do the same with updating clusters, deleting clusters and getting clusters too! And before running any of these api calls, make sure you run the following script to create the cluster table in pgAdmin first:
Select “Tools” from the top navigation bar and click on “query tools” and run the query:
That’s it! You just installed and setup your first jdbc application in spring.