Let’s add the Place Order feature to our E-commerce app using Spring Boot
Tags: ecommerce, springboot, java
Published: 2021-03-23 15:59:51


## Let’s add the Place Order feature to our E-commerce app using Spring Boot

In this tutorial, we will learn how to create an order and display the order history of the user

![](https://cdn-images-1.medium.com/max/2106/1*hcPAb0W2Ki424RtZhKKPVw.png)

## Introduction

We are building an e-commerce app from scratch using Vue.js in the frontend and Java with Spring boot for the backend. You can check out the first front-end tutorial of this series here.

{% medium https://medium.com/javarevisited/lets-develop-an-ecommerce-application-from-scratch-using-java-and-spring-6dfac6ce5a9f %}

Placing the order is an important feature for an e-commerce app that allows users to order the products of their choice.

We will first develop the backend API using Spring Boot and in the next tutorial, we will use this API for the frontend part of our e-commerce website.
> # Refer the [tutorial ](https://medium.com/javarevisited/lets-add-a-checkout-feature-in-spring-boot-for-our-ecommerce-app-72b12a7f3648?sk=b983c7f510e170a9bf7b4a60a644f1ea)where we implemented the checkout feature here for the backend part

## Live Demo

You can test the API at the following swagger link. You will find the cart API in order-controllersection(Run the code in your local first)

[**Swagger API**](http://localhost:8080/api/swagger-ui.html#/)

You can find the complete code at [Github](https://github.com/webtutsplus/ecommerce-backend).

## Pre-requisites

 1. Knowledge of Java, [OOP ](https://medium.com/javarevisited/my-favorite-courses-to-learn-object-oriented-programming-and-design-in-2019-197bab351733)& [Spring Boot Framework](https://medium.com/javarevisited/top-10-courses-to-learn-spring-boot-in-2020-best-of-lot-6ffce88a1b6e)

 2. Java Development Kit (JDK)

 3. [IntelliJ IDEA Ultimate](https://www.jetbrains.com/idea/download/) — open-source (Recommended)

 4. [MySQL](https://medium.com/javarevisited/top-5-courses-to-learn-mysql-in-2020-4ffada70656f)/MariaDB Database

 5. A good browser (Chrome — recommended)

## Project Structure

![](https://cdn-images-1.medium.com/max/2000/1*7VGLZQj-6tGFBc3CDjw2lw.png)

![](https://cdn-images-1.medium.com/max/2000/1*lYJwH_lXc9A107IxZcc00w.png)

## Preview of the API we will be building

![](https://cdn-images-1.medium.com/max/2000/1*eE9F0umd_l2_IQKc-NLmjQ.png)

**placeOrder(/order/add)** : This is a post method that is responsible for saving the order of the user.

![Post body of the method](https://cdn-images-1.medium.com/max/2122/1*uAAfvHCI6QH4HijfwT33LA.png)

**getAllOrders(/order/)**: This is a get method that returns the list of all the orders of a particular user. Therefore it requires only the token of the user as a parameter.

![](https://cdn-images-1.medium.com/max/2000/1*xg-Bcoj0yeImWguXXBBvQw.png)

## The flow of the tutorial
> # Table/Model design
> # Create Repository
> # Implement [Dto](https://javarevisited.blogspot.com/2013/01/data-access-object-dao-design-pattern-java-tutorial-example.html#axzz5b2noKDk3)
> # Implement Service class (Business logic)
> # Implement Controller class (Building APIs)

## Table Design

### Model

Before we begin to code, we must invest some time thinking about the model/table design. So we require two tables which will be linked with each other. So in the existing modelpackage, create two files Order.java and OrderItem.java .

**The first table/model** (we name it as order)will contain attributes such as id(primary key), user_id(foreign key), created_date, session-id (the payment session-id we generated), and the total_price .

***User id we will be fetching from the users table.***
>  If you are wondering about the session id, please refer to [this tutorial](https://medium.com/javarevisited/lets-add-a-checkout-feature-in-spring-boot-for-our-ecommerce-app-72b12a7f3648?sk=b983c7f510e170a9bf7b4a60a644f1ea) where we have explained the checkout session.

**The second table/model** (we name it as orderitems) will actually contain the products that are present in a particular order. There we need to link these two tables. So the [primary key](https://www.java67.com/2015/12/difference-between-primary-and-foreign.html) i.e. idfrom the order table will be used as a foreign key in the orderitems table. So the attributes of the orderitems table will be order_item_id, created_date, price, product_id(foreign key), quantity, order_id(foreign key).

***Product id we will be obtained from the products table.***

### Order model

**Table relationship**

order table and orderitems table has a relation type of one to many, i.e. one row(entry) in order table is related to multiple rows(items of that particular order) in the orderitems table.

Similarly, order and user tables have a relation type of many to one i.e. multiple orders (entries/rows) are related to a single user (row/entry), because a user may have multiple orders.
{% gist https://gist.github.com/SudhanshuGulhane/9a597c18b40d196c7da48945e84d01ee.js %}
### Order items model

**Table relationship**

The ordertable we created just now and this orderitems table has a relation type of many to one since multiple items (products) can be in relation with a particular order.

products table and the orderitems table has a relation type of one to one since a row(item) in the orderitems table is related to only one row(item) in the products table.
{% gist https://gist.github.com/SudhanshuGulhane/0153fd57fdb397ea973d99d848a6367a.js %}
## Repository

Create two java files in the existing repository package OrderRespository.java and OrderItemsRespository.java .

 1. Firstly we create repository interface for the order table(OrderRespository.java).

Creating CRUD methods manually means writing a lot of boilerplate code unless you let the JPARepository interface carry about routine implementations for you. So, we will extend the JPARepository and create the interface CartRepository.

* Extending JPARepository will automatically create and implement methods for the basic CRUD operations.

* We will define a method findAllByUserIdOrderByCreatedDateDesc to fetch the orders list of a user and then order the list by created the date of each entry in the order table. The implementation of this method will be managed automatically by the JPARepository .
{% gist https://gist.github.com/SudhanshuGulhane/bd9f315b912c8e5cdc0bc241f65f391f.js %}
2. Similarly we create repository interface for the orderitems table(OrderItemsRespository.java).
{% gist https://gist.github.com/SudhanshuGulhane/4c9ee36dbb71c0546166ad7df088959e.js %}
We do not declare any method here but instead, we will use one method in the service class later.

## DTO

In the dto package create a package named order and in which create 3 files orderDto.java , OrderItemsDto.java and placeOrderDto.java .

 1. We create OrderDto for as a dummy object for the Order model with two fields id and userId .
{% gist https://gist.github.com/SudhanshuGulhane/f2ecedc84bf5f595a3b0a55f911f63df.js %}
2. Similarly we create OrderItemsDto
{% gist https://gist.github.com/SudhanshuGulhane/73c7d3c27391986ebfa4e4dcba2dcc34.js %}
Currently, we won't be using this DTO but for future use or modifications, we keep this dto ready.

3. Now in the PlaceOrderDto we declare three fields id, userId, and the totalCostof the order. This dto will be used to save the order in the order table.
{% gist https://gist.github.com/SudhanshuGulhane/2cd8f59c248b732bdcd28205f648143b.js %}
## Service

Now, let’s implement the Service class to interact with the order and orderitems table. In the OrderRepositoryinterface, we defined the methods to interact with the [database](https://medium.com/hackernoon/top-5-sql-and-database-courses-to-learn-online-48424533ac61).

In the Service class, we will call these methods and implement the so-called business logic. We will create methods for adding the order, fetching all orders of a user. Inside these methods, we will call the methods defined in the OrderRepositoryinterface.

 1. First, let’s implement the orderitems service class. In this class, we implement one method in order to save an item/product in a particular order.
{% gist https://gist.github.com/SudhanshuGulhane/8cb821b78307794f85be6f8cc4b4455f.js %}
2. Now let’s create the order service class which will contain the logic for placing the order and fetching the order details.

placeOrder: This method is used to set the PlaceOrderDto and it receives the id of the order from the saveOrder method. This id is returned from the saveOrder method because we need this id as an attribute in the orderItems table. Also using the object of cartService class we fetch the items in the cart and then save those in the orderitems table using the method in the orderItemsService class. And once the order is placed we delete the cart i.e. remove the items in the cart.
{% gist https://gist.github.com/SudhanshuGulhane/36a642406374cc67b7aee7261744d6ef.js %}
saveOrder: This method first creates the order object and then using the method of orderRepository it saves the order in the order table and returns the id which we used in the previous method.

listOrders : This method will take the user id as a parameter and then return a list of all the orders from the order table corresponding to that user id.

## Controller

*Here we will build our APIs.*

In the controller package creates a file OrderController.java and annotate the class with [RestController annotation](https://javarevisited.blogspot.com/2017/08/difference-between-restcontroller-and-controller-annotations-spring-mvc-rest.html#ixzz6OYNB9oii). In this OrderController class, we will use the methods we defined in the orderService class.

 1. So firstly we will implement the API for saving the order. Create a method placeOrder that accepts token and the session Id as parameters.

This method which throws an exception

* if the invalid user(not logged in) user tries to place the order

* if the user (valid) tries to place the order of the product which does not exist in the products table.

![](https://cdn-images-1.medium.com/max/2400/1*fEViCrtG6PBPPc7_HoCUUQ.gif)
{% gist https://gist.github.com/SudhanshuGulhane/3f7e9373a4f656e1a1f84ffe0d0ea1cc.js %}
2. Since we added the order to the table, now we build an API to fetch the orders of the user. This method throws an exception if an invalid user tries to fetch the order history.

![](https://cdn-images-1.medium.com/max/2000/1*nirp8OQ318T89ArOwrXwig.png)

![the response body for fetching the orders of a user method](https://cdn-images-1.medium.com/max/2000/1*Uf0ZuWg5BSB8CCOyKYDOPQ.png)
{% gist https://gist.github.com/SudhanshuGulhane/fc2b5c9156485236aaebd96ba0db925a.js %}
## Congratulations!!!

We have now successfully added the order feature to our e-commerce app using Spring Boot. In the next tutorial we will implement the front end part using these APIs using Vuejs, so stay tuned!