Let’s Create a WishList for Our e-Commerce App using Java and Spring Boot
We will create a back-end of a very important feature in every e-Commerce site — Wishlist, using Java and Spring Boot
A Wishlist is an eCommerce feature that allows shoppers to create personalized collections of products they want to buy and save them in their user account. It is a must-have feature for eCommerce applications.
We will first develop the back-end API using Java & Spring Boot (in this tutorial). After the API has been created, we will use that API in our Vue.Js front-end and Android front-end (in other tutorials).
Youtube Discussion
Discussion about Wishlist feature of E-commerce appLive Demo
You can test the API at the following swagger link. You will find the wishlist API in wish-list-controller
section.
Swagger UI
You can find the complete code at Github.
Pre-requisites
- Knowledge of Java, OOP & Spring Boot Framework
- Java Development Kit (JDK)
- IntelliJ IDEA Ultimate — open-source (Recommended)
- MySQL/MariaDB Database
- A good browser (Chrome — recommended)
This tutorial is part of our series on Back-end Development with Java. We will extend the code which we developed in the previous tutorials in this series. So, if you have any doubt regarding anything that we developed earlier, you can read about it in the corresponding tutorial in the series.
Project Structure
If you have not read the previous tutorials in the back-end series, don’t worry. This section is specifically for you. As we will use the project structure that we created in the previous tutorials, we intend to describe the structure here before we begin working on the Wishlist feature. This will help you in understanding the code in a better way.
Following is the project structure:
Project Structure of the API We will now describe the following directories:-controller
— contains the controllers for various API endpointsdto
— contains the Data Transfer Objects (DTO) for our back-end. In client-server projects, data is often structured differently. There are some details in the database that we do not want to send as a response to the API calls. So, the server stores its information in a database-friendly way. While retrieving that information from the database, it can use DTOs to filter this information and then send it to the client. Don’t worry if you could not understand DTOs. You will understand it when we implement Wishlist DTO in this tutorial.model
— contains the data models (and entities)repository
— contains the methods for CRUD operations in corresponding tables of the databaseservice
— contains the class files with@service
annotations. These class files are used to write business logic in a different layer, separated from@RestController
class files. Business logic or domain logic is that part of the program which encodes the real-world business rules that determine how data can be created, stored, and changed inside the database.
API Design
Before we begin to code, we must spend some time to think about the API design and the database design. Let’s begin with the API design.
Currently, we need only two API endpoints:-
- Adding to wishlist
- Getting wishlist
Also, we had already added the token-based authorization in our eCommerce backend. So, instead of user id, we will pass the token to every endpoint of the API. Hence, we decide to have the following endpoints.
Also, in the body of the POST method, we will have to send the id of the product so that the given product can be added to the corresponding user’s wishlist. Hence, the body of the POST request should look like the following Now, the response of the POST request should send the list of all products in the wishlist with the necessary details. Hence, the response should look like the following
Table Design
Now, let’s discuss the table design. We had already created the ecommerce
database in previous tutorials. In this database, we will create a new table called wishlist.
We will keep the design simple.
The database should have three columns — id, user_id, product_id,created_date
. Here,
id
is the primary key and will be auto-generateduser_id
— stores userIdproduct_id
— stores the product idcreated_date
— stores the data & time at which the entry was created
The schema of the database looks like the following:-
CREATE TABLE `wishlist` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`created_date` timestamp NOT NULL DEFAULT current_timestamp(),
`product_id` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK6p7qhvy1bfkri13u29x6pu8au` (`product_id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4;
Ideally, each user’s wishlist should have a particular product only once. But for simplicity, we are not considering such cases.
Let’s Code
We will now begin to write code.
Model (Entity)
Let’s begin with writing the code for the Model class of each entry in the wishlist table. If you are familiar with Spring Boot or any other MVC framework, you would know that Model class is used to store each entry of the table. In Spring Boot, we use Annotations to map the columns of the table with the class members.
To create the model class, create a new class inside the Model
directory. We will call this class — WishList
.
- We have already described the schema of the table. Using the schema, we will create the class variables of the model class representing each column of the database.
- We will also create one class object of
Product
class. This object will store all the details of the product like name, price, description etc. - Also, note that the column
created_date
should be filled with the current date and time. For this, we will use thejava.util.Date
class.
Following is the complete code of WishList.java
package com.webtutsplus.ecommerce.model;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.sql.Timestamp;
import java.util.Date;
//Defining the table
@Entity
@Table(name = "wishlist")
public class WishList {
//id column
//auto generated & auto incremented
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
//user_id column
@Column(name = "user_id")
private @NotBlank Integer userId;
//product_id column
@Column(name = "product_id")
private @NotBlank Long productId;
//created_date column
@Column(name = "created_date")
private Date createdDate;
//Object of product class to store the product information
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "product_id", referencedColumnName = "id", insertable = false, updatable = false)
private Product product;
public WishList() {
}
public WishList(Integer userId, Long productId) {
this.userId = userId;
this.productId=productId;
//storing the current data & time in created_date column
this.createdDate = new Date();
}
//Setter & Getters
public Integer getId() {
return id;
}
public Long getProductId() {
return productId;
}
public Integer getUserId() {
return userId;
}
public void setId(Integer id) {
this.id = id;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public void setCreatedDate(Timestamp createdDate) {
this.createdDate = createdDate;
}
public Date getCreatedDate() {
return createdDate;
}
public void setProduct(Product product) {
this.product = product;
}
public Product getProduct() {
return product;
}
}
Repository
It is time to create the repository interface
for the wishlist
table. Create a new file called WishListRepository.java
inside the Repository directory.
If you are familiar with Spring Boot, you would know that Repository
the interface contains methods to fetch data from the table.
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 WishListRepository
.
- Extending
JPARepository
will automatically create and implement methods for the basic CRUD operations. - We will define a method
findAllByUserIdOrderByCreatedDateDesc()
to fetch the wishlist of a user and order the list by created the date of each entry in the wishlist. The implementation of this method will be managed automatically by theJPARepository
.
Following is the complete code of WishListRepository.java
package com.webtutsplus.ecommerce.repository;
import com.webtutsplus.ecommerce.model.WishList;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface WishListRepository extends JpaRepository<WishList, Integer> {
//Method for fetching the wishlist of a particular user and order it by created_date
List<WishList> findAllByUserIdOrderByCreatedDateDesc(Integer userId);
}
Service
Now, let's implement the Service
class to interact with the wishlist
table. In the WishListRepository
interface, we defined the methods to interact with the database.
In the Service
class, we will call these methods and implement the so-called business logic. To keep things simple, we do not have any business logic, i.e. business constraints or rules defined. So, we will simply create two methods createWishlist()
and readWishlist()
. Inside these methods, we will call the methods defined in the WishListRepository interface.
Following is the complete code of WishListService.java
package com.webtutsplus.ecommerce.service;
import java.util.List;
import javax.transaction.Transactional;
import com.webtutsplus.ecommerce.model.WishList;
import com.webtutsplus.ecommerce.repository.WishListRepository;
import org.springframework.stereotype.Service;
@Service
@Transactional
public class WishListService {
private final WishListRepository wishListRepository;
public WishListService(WishListRepository wishListRepository) {
this.wishListRepository = wishListRepository;
}
//Create Wishlist
public void createWishlist(WishList wishList) {
wishListRepository.save(wishList);
}
//ReadWishlist
public List<WishList> readWishList(Integer userId) {
return wishListRepository.findAllByUserIdOrderByCreatedDateDesc(userId);
}
}
Controller
Now, Let’s begin with writing code for the controller. If you are familiar with Spring Boot or any other MVC framework, you would already know that controller defines the endpoints of the API.
Create a new file inside the Controller directory with the name WishlistController.java
. Since we have two endpoints, we will create two methods in the WishlistController
class.
- To use the
WishListService
andAuthenticationService
, we will create the two objects of respective types. We have already created theWishListService
in the previous section and is used to interact with the database. We createdAuthenticationService
in a previous tutorial and is used to fetch user id of the corresponding token - We will create one method with
@GetMapping
for the GET request and@PostMapping
for the POST request. - Now, each table entry contains the
created_date
value also. We do not want to send that with the response. So, here comes the use of DTO. Using thegetDtoFromProduct()
method of theProductService
Class, we will store only that information about each product which we want to send as response. Hence, we create a list ofProductDto
object and store only the required details. We will send this list in the response.
The following is the complete code of WishlistController.java
@RestController
@RequestMapping("/wishlist")
public class WishListController {
@Autowired
private WishListService wishListService;
@Autowired
private AuthenticationService authenticationService;
//GET wishlist/token_string
@GetMapping("/{token}")
public ResponseEntity<List<ProductDto>> getWishList(@PathVariable("token") String token) {
//get userId from token
int user_id = authenticationService.getUser(token).getId();
//get wishlist
List<WishList> body = wishListService.readWishList(user_id);
//create productDTO from productId in wishlist
List<ProductDto> products = new ArrayList<ProductDto>();
for (WishList wishList : body) {
products.add(ProductService.getDtoFromProduct(wishList.getProduct()));
}
return new ResponseEntity<List<ProductDto>>(products, HttpStatus.OK);
}
//POST wishlist/add/token=token_string
@PostMapping("/add")
public ResponseEntity<ApiResponse> addWishList(@RequestBody Product product, @RequestParam("token") String token) {
//get userId from token
int userId = authenticationService.getUser(token).getId();
//add to wishlist
WishList wishList = new WishList(userId, product.getId());
wishListService.createWishlist(wishList);
//return the response
return new ResponseEntity<ApiResponse>(new ApiResponse(true, "Add to wishlist"), HttpStatus.CREATED);
}
}
`
Congratulations!!!
Congratulations, we have now added the wishlist feature to our backend.
Suggested PRs
If you wish to contribute to our eCommerce-backend, you clone this Github repository and work on the following features related to the wishlist
- Create an API end-point for Deleting a Product from Wishlist
After you have implemented the feature, send us a PR. We will review and merge it into our master branch
Reference
Let's develop an commerce application from scratch using java and spring
Let's buid signup,signing and role based access In our e-commerce app