0% found this document useful (0 votes)
6 views

Spring+Boot+eCommerce+Masterclass

Uploaded by

abhimanyu thakur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Spring+Boot+eCommerce+Masterclass

Uploaded by

abhimanyu thakur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 337

© Faisal Memon | EmbarkX.

com

Spring Boot eCommerce Masterclass

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com
Usage Policy for Course Materials

Instructor: Faisal Memon


Company: EmbarkX.com

1. Personal Use Only


The materials provided in this course, including but not limited to PDF presentations, are intended for your personal use only. They are to be
used solely for the purpose of learning and completing this course.

2. No Unauthorized Sharing or Distribution


You are not permitted to share, distribute, or publicly post any course materials on any websites, social media platforms, or other public
forums without prior written consent from the instructor.

3. Intellectual Property
All course materials are protected by copyright laws and are the intellectual property of Faisal Memon and EmbarkX. Unauthorized use,
reproduction, or distribution of these materials is strictly prohibited.

4. Reporting Violations
If you become aware of any unauthorized sharing or distribution of course materials, please report it immediately to
[[email protected]].

5. Legal Action
We reserve the right to take legal action against individuals or entities found to be violating this usage policy.

Thank you for respecting these guidelines and helping us maintain the integrity of our course materials.

Contact Information
[email protected]
www.embarkx.com
© Faisal Memon | EmbarkX.com

How Does the Web Work?

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Internet Web

Internet is a global World Wide Web is a way


network of computers of accessing information
connected over the medium of the
Internet
© Faisal Memon | EmbarkX.com

How Web Works

Server

Request
© Faisal Memon | EmbarkX.com

How Web Works

www.domainname.com IP Address
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

What is Client & Server?

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

What is a Client?
→ A device or application that requests
services or resources from a server

→ A client is typically a web browser that


Client
users interact with to access web pages

→ A client can also be other types of


software like an email client or a mobile app
© Faisal Memon | EmbarkX.com

Characteristics of a Client
→ User Interface

→ Requests Services
Client

→ Receives Data
© Faisal Memon | EmbarkX.com

What is a Server?
→ A device or application that provides
services or resources to clients
Server
→ A Server is designed to handle requests
from multiple clients

→ A Server hosts websites and respond to


requests
© Faisal Memon | EmbarkX.com

Characteristics of a Server
→ Always On

Server
→ Handles Multiple Requests

→ Sends Data
© Faisal Memon | EmbarkX.com

How do they interact?

Request

Response

Server

Request
Response
© Faisal Memon | EmbarkX.com

Examples
→ Web Browsing

→ Email
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

What Are APIs

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

API stands for Application


Programming Interface
© Faisal Memon | EmbarkX.com

Imagine you
are at a
Restaurant
© Faisal Memon | EmbarkX.com

Restaurant
Customer → Application

Kitchen → Another System Service

Menu → API Specifications

Waiter → API

Food → Response
© Faisal Memon | EmbarkX.com

API’s on server interact with


backend code on server checks
Web app in if its valid user
browser
Request

Internet Database
Browser
API
Response

Server
© Faisal Memon | EmbarkX.com

API’s can be

Private

Partner

Public
© Faisal Memon | EmbarkX.com

The Need
→ Reduces manual effort

→ Automates everything
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Types of API Requests

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Types of API requests

GET Request

POST Request

PUT Request

DELETE Request
© Faisal Memon | EmbarkX.com

GET Request
→ Retrieve or GET resources from server

→ Used only to read data


© Faisal Memon | EmbarkX.com

POST Request
→ Create resources from server
© Faisal Memon | EmbarkX.com

PUT Request
→ Update existing resources on Server
© Faisal Memon | EmbarkX.com

DELETE Request
→ Used to DELETE resources from Server
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

What is REST API and its


Architecture?

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

REST API, stands for


Representational State
Transfer Application
Programming Interface
© Faisal Memon | EmbarkX.com

REST is stateless
© Faisal Memon | EmbarkX.com

Principles of REST API


→ Client-Server Architecture

→ Stateless

→ Can be Cached

→ Opaque in terms of Layers

→ Uniform Interface
© Faisal Memon | EmbarkX.com

Web services built following


the REST architectural style
are known as RESTful web
services
© Faisal Memon | EmbarkX.com

Common Methods
→ GET

→ POST

→ PUT

→ DELETE
© Faisal Memon | EmbarkX.com

Benefits
→ Simplicity

→ Scalability

→ Flexibility

→ Visibility
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

http vs https

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

http stands for


HyperText Transfer
Protocol
© Faisal Memon | EmbarkX.com

https stands for


HyperText Transfer
Protocol Secure
© Faisal Memon | EmbarkX.com

HTTPS is essentially
HTTP with security
© Faisal Memon | EmbarkX.com

Http and Https


→ Both HTTP and HTTPS are protocols designed for transferring hypertext
across the World Wide Web.
→ They operate based on a client-server model, where a client (web browser)
sends a request to the server hosting a website
→ Both protocols use similar methods to perform actions on the web server as
well as status codes
→ HTTP and HTTPS are both stateless protocols, meaning they do not inherently
remember anything about the previous web session
→ Both HTTP and HTTPS can transfer data in various formats including HTML,
XML, JSON, and plain text
© Faisal Memon | EmbarkX.com

Thank You
© Faisal Memon | EmbarkX.com

Status Codes in API

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Need for Status Codes

Request

Response
with status
code

Cloud Server

Request
Response
with status
code
© Faisal Memon | EmbarkX.com

Classification of Status Codes


→ 1xx (Informational)

→ 2xx (Successful)

→ 3xx (Redirection)

→ 4xx (Client Error)

→ 5xx (Server Error)


© Faisal Memon | EmbarkX.com

Commonly used Status Codes


→ 200 OK

→ 201 Created

→ 204 No Content

→ 301 Moved Permanently

→ 400 Bad Request


© Faisal Memon | EmbarkX.com

Commonly used Status Codes


→ 401 Unauthorized

→ 403 Forbidden

→ 404 Not Found

→ 500 Internal Server Error


© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

What is Resource, URI and


Sub-Resource

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Resource
→ A Resource is any piece of information that can be named or identified on the
web.
→ Can represent any type of object, data, or service that can be accessed by
clients

→ A resource is not just limited to documents or files; it can be anything from a


text file, an image, a collection of other resources, a non-virtual object like a
person, and even abstract concepts like a service

→ In a social media application, resources could include a user profile, a photo, a


list of friends, or even a specific post or comment.
© Faisal Memon | EmbarkX.com

URI (Uniform Resource Identifier)


→ A URI is a string of characters used to identify a resource on the internet either
by location, name, or both
→ It provides a mechanism for accessing the representation of a resource over the
network, typically through specific protocols such as HTTP or HTTPS.

→ URIs are a broad category that includes both URLs (Uniform Resource
Locators) and URNs (Uniform Resource Names).
© Faisal Memon | EmbarkX.com

Sub-Resource
→ A Sub-Resource is a resource that is hierarchically under another resource.

→ It's a part of a larger resource and can be accessed by extending the URI of the
parent resource.
→ Sub-resources are often used in RESTful APIs to maintain a logical hierarchy of
data and to facilitate easy access to related resources.
→ Example: In a blogging platform, you might have a users resource identified by
a URI (/users). A specific user could be a resource accessible at /users/{userId}.
→ If each user can have blog posts, a post would be a sub-resource of that user,
identified by something like /users/{userId}/posts/{postId}.
© Faisal Memon | EmbarkX.com

Importance in Web Development


→ Organization

→ Accessibility

→ Scalability
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Spring Boot eCommerce Masterclass


© Faisal Memon | EmbarkX.com

What is a Web Framework?

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Why do you need Web Framework?


→ Websites have a lot in common

→ Security, Databases, URLs, Authentication….more

→ Should you do this everytime from scratch?


© Faisal Memon | EmbarkX.com

Think of building a House


→ You would need Blueprint and Tools

→ That’s how web development works

→ Developers had to build from scratch


© Faisal Memon | EmbarkX.com

What if…
→ You could have prefabricated components?

→ Could you assemble faster?

→ Could you reduce errors?

→ Would that make you fast?


© Faisal Memon | EmbarkX.com

This is what a Web


Framework does!
© Faisal Memon | EmbarkX.com

What is Web Framework


Web Framework is nothing but collection of tools and modules that
is needed to do standard tasks across every web application.
© Faisal Memon | EmbarkX.com

Popular Web Frameworks

Spring Boot (Java)

Django (Python)

Flask (Python)

Express (JavaScript)

Ruby on Rails (Ruby)


© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Introduction to Spring
Framework

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

History
→ Initially developed by Rod Johnson in 2002

→ First version released in March 2004

→ Since then, major developments and versions


released
© Faisal Memon | EmbarkX.com

Spring simplifies enterprise


application development
© Faisal Memon | EmbarkX.com

Key Principles

Simplicity

Modularity

Testability
© Faisal Memon | EmbarkX.com

Key Components of Spring


→ Core Spring Framework

→ Spring Boot

→ Spring Data

→ Spring Security

→ Spring Cloud
© Faisal Memon | EmbarkX.com

Use Cases
→ Enterprise Applications

→ Microservices Architecture

→ Web Applications
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Tight Coupling and Loose


Coupling

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Coupling refers to how


closely connected different
components or systems are
© Faisal Memon | EmbarkX.com

Tight Coupling

Tight coupling describes a


scenario where software
components are highly
dependent on each other
© Faisal Memon | EmbarkX.com

Loose Coupling

Loose coupling describes a


scenario where software
components are less
dependent on each other
© Faisal Memon | EmbarkX.com

Importance in Software Design


→ Flexibility and Maintainability

→ Scalability

→ Testing
© Faisal Memon | EmbarkX.com

Achieving Loose Coupling

Interfaces and Abstraction

Dependency Injection

Event Driven Architecture


© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Core Concepts of Spring

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Loose Coupling
Loose Coupling is a design principle that aims to reduce the
dependencies between components within a system
© Faisal Memon | EmbarkX.com

Inversion of Control (IoC)

Inversion of Control is a design principle where the control of object


creation and lifecycle management is transferred from the
application code to an external container or framework
© Faisal Memon | EmbarkX.com

Dependency Injection [DI]


Dependency injection is a design pattern commonly used in
object-oriented programming, where the dependencies of a class
are provided externally rather than being created within the class
itself
© Faisal Memon | EmbarkX.com

Beans

Objects that are managed by frameworks are known as Beans


© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Spring Container and


Configuration

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Spring Container
© Faisal Memon | EmbarkX.com

Types of Spring Containers

ApplicationContext

BeanFactory
© Faisal Memon | EmbarkX.com

Spring Container
© Faisal Memon | EmbarkX.com

Spring Container

Config
© Faisal Memon | EmbarkX.com

Configuration contains
bean definition
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Lifecycle of Bean

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Beans

Objects that are managed by frameworks are known as Beans


© Faisal Memon | EmbarkX.com

Beans
Bean Definition
● A bean definition includes configuration metadata that the container needs
to know to create and manage the bean

Bean Configuration
● Bean definitions can be provided in various ways, including XML
configuration files, annotations, and Java-based configuration.
● Beans are configured using XML files, where each bean is defined within
<bean> tags with attributes specifying class, properties, and dependencies.
● Beans can be configured using annotations like @Component, @Service,
@Repository, etc., which are scanned by Spring and managed as beans.
© Faisal Memon | EmbarkX.com

Lifecycle of Beans

Population of
Instantiation Initialization
Properties

Destruction Ready for use


© Faisal Memon | EmbarkX.com

Dependency Resolution
→ Dependency Injection

→ Autowiring
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Dependency Injection (DI)

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Dependency Injection (DI) is a design


pattern used in software development to
achieve loose coupling between classes by
removing the direct dependency
instantiation from the dependent class
itself
© Faisal Memon | EmbarkX.com

Types
→ Constructor Injection

→ Setter Injection
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Constructor Injection

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Constructor Injection
→ Dependencies are provided to the dependent class through
its constructor
→ Dependencies are passed as arguments to the constructor
when the dependent class is instantiated
→ Constructor injection ensures that the dependencies are
available when the object is created
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Setter Injection

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Setter Injection
→ Dependencies are provided to the dependent class through
setter methods
→ Dependent class exposes setter methods for each
dependency that needs to be injected
→ Setter injection allows for flexibility as dependencies can be
changed or updated after the object is instantiated
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Introduction to Annotations

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Annotations in Java
provide a way to add
metadata to your code
© Faisal Memon | EmbarkX.com

@Override
© Faisal Memon | EmbarkX.com

Commonly Used Spring Annotations


→ @Component

→ @Autowired

→ @Qualifier

→ @Value

→ @Repository
© Faisal Memon | EmbarkX.com

Commonly Used Spring Annotations


→ @Service

→ @Controller

→ @RequestMapping

→ @SpringBootApplication
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Understanding Components
and ComponentScan

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Component refers to a Java


class that is managed by the
Spring IoC container
© Faisal Memon | EmbarkX.com

Defining Components in Spring

Using XML

Using Annotations
© Faisal Memon | EmbarkX.com

Using XML

<bean id="myComponent" class="com.example.MyComponent" />


© Faisal Memon | EmbarkX.com

Using Annotations
import org.springframework.stereotype.Component;

@Component // Marks the class as a Spring component


public class MyComponent {
// Class implementation
}
© Faisal Memon | EmbarkX.com

Component scanning is a
feature helps to automatically
detect and register beans from
predefined package paths.
© Faisal Memon | EmbarkX.com

Using XML

<!-- Enable component scanning -->


<context:component-scan base-package="car.example.componentscan"/>
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Progress and Review So Far

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Review

Spring
Basics of Web Coupling
Framework

Xml &
DI and IoC Configurations
Annotations
© Faisal Memon | EmbarkX.com

Review
→ Explicit Bean Configuration

→ No Embedded Server

→ Component Scanning

→ Boilerplate code
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

What is Spring Boot?

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

What is Spring Boot?


Open-source, Java-based framework used to create stand-alone,
production-grade Spring-based Applications
© Faisal Memon | EmbarkX.com

Spring VS Spring Boot

Offers a set of
pre-configured
Lots of steps involved in components or defaults,
setting up, configuration, and eliminating the need
writing boilerplate code, for a lot of boilerplate
deployment of the app code that was involved in
setting up a Spring
application
© Faisal Memon | EmbarkX.com

Spring Framework
+
Spring boot = Prebuilt Configuration

+
Embedded Servers
© Faisal Memon | EmbarkX.com

Components of Spring Boot


→ Spring Boot Starters

→ Auto Configuration

→ Spring Boot Actuator


→ Embedded Server

→ Spring Boot DevTools


© Faisal Memon | EmbarkX.com

Advantages of Spring Boot


→ Stand alone and Quick Start

→ Starter code

→ Less configuration
→ Reduced cost and application development time
© Faisal Memon | EmbarkX.com

Why do developers love Spring Boot?


→ Java based

→ Fast, easy

→ Comes with embedded server


→ Various plugins

→ Avoids boilerplate code and configurations


© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Structuring Thoughts

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

OUR APPLICATION

Controller Service

Browser Category Category

Response Back

SERVER
OUR APPLICATION © Faisal Memon | EmbarkX.com

Controller Service Repository

Address Address Address

Auth Auth Auth


Database

Cart Cart Cart


Browser
Category Category Category

Order Order Order

Product Product Product

Response Back

SERVER
© Faisal Memon | EmbarkX.com

Request Request

API Name Endpoint Method Purpose Body Parameters Response

Create Create a new


/api/admin/category POST Category None CategoryDTO
Category category

pageNumber,
Get Retrieve a list
/api/public/categories GET None pageSize, sortBy, CategoryResponse
Categories of categories
sortOrder

Update an
Update
/api/admin/categories/{categoryId} PUT existing Category categoryId CategoryDTO
Category
category

Delete an
Delete
/api/admin/categories/{categoryId} DELETE existing None categoryId CategoryDTO
Category
category
© Faisal Memon | EmbarkX.com

Request Request

API Name Endpoint Method Purpose Body Parameters Response

Create Create a new


/api/admin/category POST Category None CategoryDTO
Category category

pageNumber,
Get Retrieve a list
/api/public/categories GET None pageSize, sortBy, CategoryResponse
Categories of categories
sortOrder

Update an
Update
/api/admin/categories/{categoryId} PUT existing Category categoryId CategoryDTO
Category
category

Delete an
Delete
/api/admin/categories/{categoryId} DELETE existing None categoryId CategoryDTO
Category
category
© Faisal Memon | EmbarkX.com

Request Request

API Name Endpoint Method Purpose Body Parameters Response

Create Create a new


/api/admin/category POST Category None CategoryDTO
Category category

pageNumber,
Get Retrieve a list
/api/public/categories GET None pageSize, sortBy, CategoryResponse
Categories of categories
sortOrder

Update an
Update
/api/admin/categories/{categoryId} PUT existing Category categoryId CategoryDTO
Category
category

Delete an
Delete
/api/admin/categories/{categoryId} DELETE existing None categoryId CategoryDTO
Category
category
© Faisal Memon | EmbarkX.com

Request Request

API Name Endpoint Method Purpose Body Parameters Response

Create Create a new


/api/admin/category POST Category None CategoryDTO
Category category

pageNumber,
Get Retrieve a list
/api/public/categories GET None pageSize, sortBy, CategoryResponse
Categories of categories
sortOrder

Update an
Update
/api/admin/categories/{categoryId} PUT existing Category categoryId CategoryDTO
Category
category

Delete an
Delete
/api/admin/categories/{categoryId} DELETE existing None categoryId CategoryDTO
Category
category
© Faisal Memon | EmbarkX.com

Request Request

API Name Endpoint Method Purpose Body Parameters Response

Create Create a new


/api/admin/category POST Category None CategoryDTO
Category category

pageNumber,
Get Retrieve a list
/api/public/categories GET None pageSize, sortBy, CategoryResponse
Categories of categories
sortOrder

Update an
Update
/api/admin/categories/{categoryId} PUT existing Category categoryId CategoryDTO
Category
category

Delete an
Delete
/api/admin/categories/{categoryId} DELETE existing None categoryId CategoryDTO
Category
category
© Faisal Memon | EmbarkX.com

Request Request

API Name Endpoint Method Purpose Body Parameters Response

Create Create a new


/api/admin/category POST Category None CategoryDTO
Category category

pageNumber,
Get Retrieve a list
/api/public/categories GET None pageSize, sortBy, CategoryResponse
Categories of categories
sortOrder

Update an
Update
/api/admin/categories/{categoryId} PUT existing Category categoryId CategoryDTO
Category
category

Delete an
Delete
/api/admin/categories/{categoryId} DELETE existing None categoryId CategoryDTO
Category
category
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Understanding Data and


Databases

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com
© Faisal Memon | EmbarkX.com

Your
Application Database
Computer Save Job
Add a Job
© Faisal Memon | EmbarkX.com

What is a Database?
Database is a place where data related to your users and product is
stored.
© Faisal Memon | EmbarkX.com

Databases Types
→ Relational

→ Non-Relational
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

What is DBMS

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

You (User) DBMS


Database
© Faisal Memon | EmbarkX.com

Examples of DBMS
→ MySQL

→ Oracle Database

→ SQL Server

→ MongoDB

→ Cassandra
© Faisal Memon | EmbarkX.com

Types of DBMS

Relational Database Management System


(RDBMS)

NoSQL Database Management System


© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Introduction to Relational
Databases Concepts

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

DBMS Terminologies

Table

Column

Row
© Faisal Memon | EmbarkX.com

DBMS Terminologies
Table

Column

Row
Primary Key

Foreign Key

Index
Query
© Faisal Memon | EmbarkX.com

column_1 column_2 column_3 column_4 ….


Row
Row 1
Or
Row 2 Tuple
Or
Record

Columns
© Faisal Memon | EmbarkX.com

Rental ID Car Make Car Model Rental Period Rental Price

1 Maruti Suzuki Vitara 3 days $150


Row
2 Jaguar F7 2 days $120
Or
3 Renault Duster 5 days $400
Tuple
4 Chevrolet Impala 7 days $700 Or
5 TATA Nexon 4 days $200 Record
6 Kia Seltos 1 day $50

7 Mahindra XUV700 10 days $1000

These are columns- may have diff datatypes


© Faisal Memon | EmbarkX.com

Rental ID Car Make Car Model Rental Period Rental Price

1 Maruti Suzuki Vitara 3 days $150

2 Jaguar F7 2 days $120

3 Renault Duster 5 days $400

4 Chevrolet Impala 7 days $700

5 TATA Nexon 4 days $200

6 Kia Seltos 1 day $50

7 Mahindra XUV700 10 days $1000


© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Overview of SQL

Faisal Memon
© Faisal Memon | EmbarkX.com

How do I get the data?

Database
© Faisal Memon | EmbarkX.com

SQL
Database
© Faisal Memon | EmbarkX.com

What is SQL
SQL stands for Structured Query Language. Used to retrieve,
manage and update data in Database
© Faisal Memon | EmbarkX.com

SQL Queries

Data from Database is retrieved with the help of SQL queries.


© Faisal Memon | EmbarkX.com

Different Types of SQL Queries


→ Data Query Language [DQL]

→ Data Manipulation Language [DML]

→ Data Definition Language [DDL]

→ Data Control Language [DCL]

→ Transaction Control Language(TCL)


© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

What is ORM?

Faisal Memon (EmbarkX)


Customer class © Faisal Memon | EmbarkX.com

Customer

id : Integer
first_name : String
last_name : String

customer_1 customer_2 customer_3

id : 1 id : 2 id : 3
first_name : “John” first_name: “Stacy” first_name : “Mark”
last_name : “Trump” last_name: “Keiber” last_name : “Dsouza”

Customer in database
id first_name last_name
1 John Trump
2 Stacy Keiber
3 Mark Dsouza
© Faisal Memon | EmbarkX.com

ORM
→ Whenever there is a class, that class can be automatically
converted to a table with its attributes being converted to columns

→ So now the developer does not have to write queries for table
creation, it's created automatically

→ Whenever an object is created, its data can be saved in the


database as row in table, this is automatically handled by ORM
© Faisal Memon | EmbarkX.com

ORM
→ ORM as a concept makes developers lives easier and lets
developers focus on application logic rather than SQL queries
→ Because of ORM developers don’t need to learn how to write
SQL queries since the translation from application to SQL is
handled by ORM itself
→ It’s a powerful technique in programming which also minimizes
mistakes since developers are not writing queries on their own
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

What is JPA?

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

class Category {
Long categoryId;
String categoryName;
}

categoryId categoryName

1 Senior Software Engineer


© Faisal Memon | EmbarkX.com

Advantages of using JPA


→ Easy and Simple

→ Makes querying easier

→ Allows to save and update objects

→ Easy integration with Spring Boot


© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Let’s Understand Data Layer

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Presentation layer presents the data and the application


Presentation Layer features to the user. This is the layer where in all the
controller classes exist.

Service layer is where business logic resides in the


Service Layer application. Tasks such as evaluations, decision making,
processing of data is done at this layer.

Data access layer is the layer where all the repository


Data Access Layer
classes reside.
© Faisal Memon | EmbarkX.com

OUR APPLICATION

Category Category Category


Browser Controller Service Repository H2 Database

Response Back
SERVER
OUR APPLICATION © Faisal Memon | EmbarkX.com

Controller Service Repository

Address Address Address

Auth Auth Auth


Database

Cart Cart Cart


Browser
Category Category Category

Order Order Order

Product Product Product

Response Back

SERVER
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Generation Types For Identity

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Different Generation Types

AUTO

IDENTITY

SEQUENCE

TABLE

NONE
© Faisal Memon | EmbarkX.com

GenerationType.AUTO

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
© Faisal Memon | EmbarkX.com

GenerationType.IDENTITY

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
© Faisal Memon | EmbarkX.com

GenerationType.SEQUENCE

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
© Faisal Memon | EmbarkX.com

GenerationType.SEQUENCE
@Id

@GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "order_seq")

@SequenceGenerator(name = "order_seq", sequenceName =


"order_sequence", allocationSize = 1)

private Long id;


© Faisal Memon | EmbarkX.com

GenerationType.SEQUENCE
@Id

@GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "order_seq")

@SequenceGenerator(name = "order_seq", sequenceName =


"order_sequence", allocationSize = 1)

private Long id;


© Faisal Memon | EmbarkX.com

GenerationType.SEQUENCE
@Id

@GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "order_seq")

@SequenceGenerator(name = "order_seq", sequenceName =


"order_sequence", allocationSize = 1)

private Long id;


© Faisal Memon | EmbarkX.com

GenerationType.SEQUENCE
@Id

@GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "order_seq")

@SequenceGenerator(name = "order_seq", sequenceName =


"order_sequence", allocationSize = 1)

private Long id;


© Faisal Memon | EmbarkX.com

GenerationType.SEQUENCE
@Id

@GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "order_seq")

@SequenceGenerator(name = "order_seq", sequenceName =


"order_sequence", allocationSize = 1)

private Long id;


© Faisal Memon | EmbarkX.com

GenerationType.SEQUENCE
@Id

@GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "order_seq")

@SequenceGenerator(name = "order_seq", sequenceName =


"order_sequence", allocationSize = 1)

private Long id;


© Faisal Memon | EmbarkX.com

GenerationType.TABLE

@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
© Faisal Memon | EmbarkX.com

GenerationType.TABLE
@Id

@GeneratedValue(strategy = GenerationType.TABLE,
generator = "task_gen")

@TableGenerator(name = "task_gen", table = "id_gen",


pkColumnName = "gen_key", valueColumnName = "gen_value",
pkColumnValue = "task_id", allocationSize = 1)

private Long id;


© Faisal Memon | EmbarkX.com

GenerationType.TABLE
@Id

@GeneratedValue(strategy = GenerationType.TABLE,
generator = "task_gen")

@TableGenerator(name = "task_gen", table = "id_gen",


pkColumnName = "gen_key", valueColumnName = "gen_value",
pkColumnValue = "task_id", allocationSize = 1)

private Long id;


© Faisal Memon | EmbarkX.com

GenerationType.TABLE
@Id

@GeneratedValue(strategy = GenerationType.TABLE,
generator = "task_gen")

@TableGenerator(name = "task_gen", table = "id_gen",


pkColumnName = "gen_key", valueColumnName = "gen_value",
pkColumnValue = "task_id", allocationSize = 1)

private Long id;


© Faisal Memon | EmbarkX.com

GenerationType.TABLE
@Id

@GeneratedValue(strategy = GenerationType.TABLE,
generator = "task_gen")

@TableGenerator(name = "task_gen", table = "id_gen",


pkColumnName = "gen_key", valueColumnName = "gen_value",
pkColumnValue = "task_id", allocationSize = 1)

private Long id;


© Faisal Memon | EmbarkX.com

GenerationType.TABLE
@Id

@GeneratedValue(strategy = GenerationType.TABLE,
generator = "task_gen")

@TableGenerator(name = "task_gen", table = "id_gen",


pkColumnName = "gen_key", valueColumnName = "gen_value",
pkColumnValue = "task_id", allocationSize = 1)

private Long id;


© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Validations in Spring Boot

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Validations in Spring Boot are all


about ensuring the data your
application receives meets certain
criteria before it's processed
© Faisal Memon | EmbarkX.com

Validation in Spring Boot


→ @NotNull

→ @NotEmpty

→ @Size(min = x, max = y)

→ @Email

→ @Min(value) and @Max(value)


© Faisal Memon | EmbarkX.com

Example
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;

public class User {


@NotEmpty(message = "Email cannot be empty")
@Email(message = "Email should be valid")
private String email;

@NotEmpty(message = "Name cannot be empty")


@Size(min = 2, message = "Name should have at least 2 characters")
private String name;

// getters and setters


}
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Custom Exceptions in Spring


Boot

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Use of ResponseStatusException
© Faisal Memon | EmbarkX.com

Why Consider Custom Exceptions Anyway?


→ Separation of Concerns

→ Consistency and Reusability

→ Detailed Error Information

→ Complex Error Handling Logic


© Faisal Memon | EmbarkX.com

Using Custom Exceptions with


ResponseStatusException
→ ResponseStatusException for direct feedback

→ Define Custom Exceptions for Business Logic

→ Handle Custom Exceptions in Controller Advice

→ Custom Exceptions for consistency


© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

DTO Pattern

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

What is it?
Design pattern used to transfer data between software application
subsystems
© Faisal Memon | EmbarkX.com

Data Transfer
JSON Category
Object
© Faisal Memon | EmbarkX.com

1. Request with
3. Get desired data
DTO
from the database
2. Converts DTO to
Entity

Client Server Database

4. Data is passed
to server

6. Response sent 5. Convert Entity


in DTO form to into DTO
Client
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Working with Multiple


Entities / Relationships

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Real world projects will


have multiple models
© Faisal Memon | EmbarkX.com

Entity relationships are


important
© Faisal Memon | EmbarkX.com

JPA and Relationships


→ An entity represents a table in your database

→ Each instance of an entity corresponds to a row in that table

→ If you have a table for storing information about books, each book object
would be a row

→ Relationships in JPA define how entities are related to each other

→ JPA allows you to map these relationships using annotations in your Java code
© Faisal Memon | EmbarkX.com

Relationships

One to One

One to Many OR Many to One

Many to Many
© Faisal Memon | EmbarkX.com

One to One Relationship


One to one relationship is a type of relationship where in one
record in a table is related to exactly one more record in another
table and vice versa
© Faisal Memon | EmbarkX.com

Example
Employee and salary account

Salary
Employee
account

Example 2 → Person and passport


© Faisal Memon | EmbarkX.com

Many to One relationship

A many to one relationship is a type of relationship when one


record in one table has one or many related record in another table
© Faisal Memon | EmbarkX.com

Example
Customer and orders Order 1

Order 1
Customer
Order 1

Users and Bank accounts


© Faisal Memon | EmbarkX.com

Many to Many relationship

A many to many relationship is a type of relationship when one


record in one table has many related record in another table
© Faisal Memon | EmbarkX.com

Example
Customer and products

Customer 1 Product 1

Product 2
Customer 1

Customer 1 Product 3

Courses and Students


© Faisal Memon | EmbarkX.com

Unidirectional Relationship

When only one entity knows about the relationship


© Faisal Memon | EmbarkX.com

Bidirectional Relationship

When both entities are aware of each other


© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

One to One Relationship

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Occurs when one record in a


table is associated with one
and only one record in
another table
© Faisal Memon | EmbarkX.com

Example

User Profile
© Faisal Memon | EmbarkX.com

Why Do We Need 1:1 Relationship

Separation of sensitive data

Optional data

Splitting for performance


© Faisal Memon | EmbarkX.com

Example
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

One to Many AND Many to


One

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Occurs when one record in


one table can be associated
with multiple records in
another table
© Faisal Memon | EmbarkX.com

Example
© Faisal Memon | EmbarkX.com

Before

BookID Title AuthorName

1 Quantum Realm Alice Smith

2 Particle Play Bob Johnson

3 Atomic Actions Alice Smith


© Faisal Memon | EmbarkX.com

After

BookID Title AuthorID


AuthorID Name
1 Quantum Realm 1
1 Alice Smith
2 Particle Play 2
2 Bob Johnson
3 Atomic Actions 1
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Many to Many Relationship

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Occurs when multiple records


in one table can be associated
with multiple records in
another table
© Faisal Memon | EmbarkX.com

Example

→ Junction table
© Faisal Memon | EmbarkX.com

Example
© Faisal Memon | EmbarkX.com

Things to remember
→ Junction table may contain additional attributes

→ Junction table helps avoid redundancy

→ To retrieve data you have to write JOIN


statements that include the junction table
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Cascading

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Cascading Types

PERSIST

MERGE

REMOVE

REFRESH

DETACH

ALL
© Faisal Memon | EmbarkX.com

FetchTypes

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

FetchType plays a crucial role in


defining how and when related
entities are loaded from the database
in relation to the parent entity
© Faisal Memon | EmbarkX.com

FetchTypes

FetchType.LAZY

FetchType.EAGER
© Faisal Memon | EmbarkX.com

Default FetchTypes
→ OneToMany: Lazy

→ ManyToOne: Eager

→ ManyToMany: Lazy

→ OneToOne: Eager
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Understanding the Product


Module

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

OUR APPLICATION

Product Product Product


Browser Controller Service Repository H2 Database

Response Back
SERVER
OUR APPLICATION © Faisal Memon | EmbarkX.com

Controller Service Repository

Address Address Address

Auth Auth Auth


Database

Cart Cart Cart


Browser
Category Category Category

Order Order Order

Product Product Product

Response Back

SERVER
© Faisal Memon | EmbarkX.com

Metho Request
API Name Endpoint d Purpose Body Request Parameters Response

Adds a new ProductDTO


Add /api/admin/categories/{categoryId}/prod Product categoryId
POST product to a (JSON), HttpStatus
Product uct (JSON) (PathVariable)
category 201

pageNumber, pageSize, ProductResponse


Get All Retrieves all
/api/public/products GET - sortBy, sortOrder (JSON), HttpStatus
Products products
(RequestParams) 200

categoryId
Get Retrieves (PathVariable), ProductResponse
/api/public/categories/{categoryId}/prod
Products by GET products by - pageNumber, pageSize, (JSON), HttpStatus
ucts
Category category sortBy, sortOrder 200
(RequestParams)

keyword
Get Searches (PathVariable), ProductResponse
Products by /api/public/products/keyword/{keyword} GET products by - pageNumber, pageSize, (JSON), HttpStatus
Keyword keyword sortBy, sortOrder 302
(RequestParams)

Updates an ProductDTO
Update Product productId
/api/products/{productId} PUT existing (JSON), HttpStatus
Product (JSON) (PathVariable)
product 200
© Faisal Memon | EmbarkX.com

Metho Request
API Name Endpoint d Purpose Body Request Parameters Response

Multipart
Update Updates the ProductDTO
File productId
Product /api/products/{productId}/image PUT image of a (JSON), HttpStatus
(Form (PathVariable)
Image product 200
Data)

String (Status
Delete DELET Deletes a productId
/api/admin/products/{productId} - Message),
Product E product (PathVariable)
HttpStatus 200

Get Retrieves pageNumber, pageSize, ProductResponse


Products by /api/seller/products GET products by - sortBy, sortOrder (JSON), HttpStatus
Seller seller (RequestParams) 200

Get
Retrieves Long, HttpStatus
Product /api/admin/products/count GET - -
product count 200
Count
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Introduction to Spring
Security

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Security is important
© Faisal Memon | EmbarkX.com

Importance of Security
→ Privacy Protection

→ Trust

→ Integrity

→ Compliance
© Faisal Memon | EmbarkX.com

Role of Spring Security within the Spring Ecosystem

→ Spring Framework

→ Spring Boot

→ Spring Data
→ Spring Security
– Authentication
– Authorization
© Faisal Memon | EmbarkX.com

Authentication and Authorization

Authentication
Authentication is proving who you are.

Authorization
Authorization is about what you're allowed to do after you've proven who you
are.
© Faisal Memon | EmbarkX.com

Authentication and Authorization

Authentication
Scanning your ID badge to confirm your identity as an employee.

Authorization
After confirming your identity, determining if you're permitted to enter certain
restricted areas based on your job role or clearance level.
© Faisal Memon | EmbarkX.com

Key Security Principles


→ Least Privilege

→ Secure by Design

→ Fail-Safe Defaults

→ Secure Communication
© Faisal Memon | EmbarkX.com

Key Security Principles


→ Input Validation

→ Auditing and Logging

→ Regular Updates and Patch Management


© Faisal Memon | EmbarkX.com

Hashing

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

What is Hashing?
© Faisal Memon | EmbarkX.com

programming

Hashing

$2a$12$JBtXfRbJBXD/lnskS7O/3eaT3hTAp/lSzdm0xaFTv7dS3SQ8tNyLW
© Faisal Memon | EmbarkX.com

Hashing involves using


Algorithms
© Faisal Memon | EmbarkX.com

bcrypt involves using


salting
© Faisal Memon | EmbarkX.com

Salting helps increase


security
© Faisal Memon | EmbarkX.com

programming XwZ78 SALT

Hashing

$2a$12$JBtXfRbJBXD/lnskS7O/3eaT3hTAp/lSzdm0xaFTv7dS3SQ8tNyLW
© Faisal Memon | EmbarkX.com

programming 7w139768b SALT

Hashing

$2a$12$xwHrcZF9BsDDoqF1JirbMu9h911nvqFUldZFcSvXE91MYTGwMLpYa
© Faisal Memon | EmbarkX.com

JWT Authentication

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Without JWT
→ No advanced features like expiration time

→ Can be decoded easily

→ Should we go for “Custom token system”


© Faisal Memon | EmbarkX.com

JWT = JSON Web


Token
© Faisal Memon | EmbarkX.com

JSON Web Tokens are


an open, industry
standard
© Faisal Memon | EmbarkX.com

1. User tries to login

2.Token
Generation

3. Token is issued to user

USER 4. Token sent in API requests SERVER

5. Token
Validated

6. Request authorized if valid, else error


© Faisal Memon | EmbarkX.com

How is Token sent

Tokens are sent using HTTP Authorization header

Format
Authorization: Bearer <token>
© Faisal Memon | EmbarkX.com

Header
PAYLOAD

VERIFY SIGNATURE
© Faisal Memon | EmbarkX.com
© Faisal Memon | EmbarkX.com

Understanding
Implementation of JWT

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

JwtUtils

AuthTokenFilter

Files we are going to need


AuthEntryPointJwt

SecurityConfig
© Faisal Memon | EmbarkX.com

JwtUtils
JwtUtils
→ Contains utility methods
for generating, parsing, and
AuthTokenFilter
validating JWTs.
AuthEntryPointJwt
→Include generating a token
from a username, validating a
SecurityConfig
JWT, and extracting the
username from a token.
© Faisal Memon | EmbarkX.com

AuthTokenFilter
→ Filters incoming requests to
JwtUtils
check for a valid JWT in the
header, setting the
AuthTokenFilter authentication context if the
token is valid.
AuthEntryPointJwt
→Extracts JWT from request
header, validates it, and
SecurityConfig configures the Spring Security
context with user details if the
token is valid.
© Faisal Memon | EmbarkX.com

AuthEntryPointJwt
→ Provides custom handling for
JwtUtils
unauthorized requests, typically
when authentication is required
AuthTokenFilter but not supplied or valid.

AuthEntryPointJwt →When an unauthorized


request is detected, it logs the
error and returns a JSON
SecurityConfig response with an error message,
status code, and the path
attempted.
© Faisal Memon | EmbarkX.com

SecurityConfig
JwtUtils → Configures Spring Security
filters and rules for the
AuthTokenFilter application

→Sets up the security filter


AuthEntryPointJwt chain, permitting or denying
access based on paths and roles.
It also configures session
SecurityConfig management to stateless, which
is crucial for JWT usage.
© Faisal Memon | EmbarkX.com

Authentication Controller

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Metho Request
API Name Endpoint d Purpose Request Body Parameters Response

LoginRequest UserInfoResponse
Sign In /signin POST Authenticate a user -
(JSON) (JSON), HttpStatus.OK

SignupRequest MessageResponse
Sign Up /signup POST Register a new user -
(JSON) (JSON), HttpStatus.OK

MessageResponse
Sign Out /signout POST Sign out the user - -
(JSON), HttpStatus.OK

Retrieve the
Current String (username),
/username GET username of the - -
Username HttpStatus.OK
authenticated user

Retrieve user UserInfoResponse


User Info /user GET - -
information (JSON), HttpStatus.OK

pageNumber
Retrieve a paginated UserResponse (JSON),
All Sellers /sellers GET - (Query
list of sellers HttpStatus.OK
Parameter)
© Faisal Memon | EmbarkX.com

Jwt Cookie Based Auth

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Bearer tokens need to be added


explicitly to the HTTP request

Format
Authorization: Bearer <token>
© Faisal Memon | EmbarkX.com

Browser will
automatically send
cookies
© Faisal Memon | EmbarkX.com

1. User tries to login

2.Token
Generation

3. Token is issued to user

USER 4. Token sent in API requests SERVER

5. Token
Validated

6. Request authorized if valid, else error


© Faisal Memon | EmbarkX.com

1. User tries to login

2.Token
Generation

3. Token is issued to user as a cookie

USER 4. JWT Cookie sent in API requests SERVER

5. Token
Validated

6. Request authorized if valid, else error


© Faisal Memon | EmbarkX.com

1. User tries to login

2.Token
Generation

3. Token is issued to user as a cookie

USER 4. JWT Cookie sent in API requests SERVER

5. Token
Validated

6. Request authorized if valid, else error


© Faisal Memon | EmbarkX.com

Thinking About Shopping


Cart

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Shopping Cart allows users to select


and store items they wish to
purchase
© Faisal Memon | EmbarkX.com

Ways to Implement Shopping Carts

Session Based Carts

Cookie Based Carts

Database Based Carts


© Faisal Memon | EmbarkX.com

Shopping Carts

Session-Based Carts
Cart's contents are stored in the user's session. If session expires, data is lost.

Cookie-Based Carts
Cart data is stored in cookies on the user's browser.

Database-Based Carts
Cart data is stored on the server side, within a database. This approach is
scalable, secure, and allows for advanced features like cart recovery, detailed
analytics, and cross-device accessibility.
© Faisal Memon | EmbarkX.com

We Will Use Database Based Carts


© Faisal Memon | EmbarkX.com

Advantages of Database-Based Carts


→ Persistence and Reliability

→ Scalability

→ Enhanced Features

→ Security

→ User Experience
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Designing Cart Module

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

OUR APPLICATION

Controller Service Repository


Database

Browser Cart Cart Cart

Response Back

SERVER
© Faisal Memon | EmbarkX.com

Request Request
API Name Endpoint Method Purpose Body Parameters Response

productId:
Add Adds a specified
/api/carts/products/{product Long, CartDTO
Product to POST product and quantity to None
Id}/quantity/{quantity} quantity: (JSON)
Cart the user's cart.
Integer

List of
Get All Retrieves a list of all
/api/carts GET None None CartDTO
Carts carts.
(JSON)

Get User's Retrieves the cart of CartDTO


/api/carts/users/cart GET None None
Cart the logged-in user. (JSON)

productId:
Update Updates the quantity of
/api/cart/products/{productI Long, CartDTO
Product PUT a specific product in the None
d}/quantity/{operation} operation: (JSON)
Quantity cart.
String

Delete Removes a specific cartId: Long, String


/api/carts/{cartId}/product/{
Product DELETE product from the user's None productId: (Status
productId}
from Cart cart. Long message)
© Faisal Memon | EmbarkX.com

Request Request
API Name Endpoint Method Purpose Body Parameters Response

productId:
Add Adds a specified
/api/carts/products/{product Long, CartDTO
Product to POST product and quantity to None
Id}/quantity/{quantity} quantity: (JSON)
Cart the user's cart.
Integer

List of
Get All Retrieves a list of all
/api/carts GET None None CartDTO
Carts carts.
(JSON)

Get User's Retrieves the cart of CartDTO


/api/carts/users/cart GET None None
Cart the logged-in user. (JSON)

productId:
Update Updates the quantity of
/api/cart/products/{productI Long, CartDTO
Product PUT a specific product in the None
d}/quantity/{operation} operation: (JSON)
Quantity cart.
String

Delete Removes a specific cartId: Long, String


/api/carts/{cartId}/product/{
Product DELETE product from the user's None productId: (Status
productId}
from Cart cart. Long message)
© Faisal Memon | EmbarkX.com

Request Request
API Name Endpoint Method Purpose Body Parameters Response

productId:
Add Adds a specified
/api/carts/products/{product Long, CartDTO
Product to POST product and quantity to None
Id}/quantity/{quantity} quantity: (JSON)
Cart the user's cart.
Integer

List of
Get All Retrieves a list of all
/api/carts GET None None CartDTO
Carts carts.
(JSON)

Get User's Retrieves the cart of CartDTO


/api/carts/users/cart GET None None
Cart the logged-in user. (JSON)

productId:
Update Updates the quantity of
/api/cart/products/{productI Long, CartDTO
Product PUT a specific product in the None
d}/quantity/{operation} operation: (JSON)
Quantity cart.
String

Delete Removes a specific cartId: Long, String


/api/carts/{cartId}/product/{
Product DELETE product from the user's None productId: (Status
productId}
from Cart cart. Long message)
© Faisal Memon | EmbarkX.com

Request Request
API Name Endpoint Method Purpose Body Parameters Response

productId:
Add Adds a specified
/api/carts/products/{product Long, CartDTO
Product to POST product and quantity to None
Id}/quantity/{quantity} quantity: (JSON)
Cart the user's cart.
Integer

List of
Get All Retrieves a list of all
/api/carts GET None None CartDTO
Carts carts.
(JSON)

Get User's Retrieves the cart of CartDTO


/api/carts/users/cart GET None None
Cart the logged-in user. (JSON)

productId:
Update Updates the quantity of
/api/cart/products/{productI Long, CartDTO
Product PUT a specific product in the None
d}/quantity/{operation} operation: (JSON)
Quantity cart.
String

Delete Removes a specific cartId: Long, String


/api/carts/{cartId}/product/{
Product DELETE product from the user's None productId: (Status
productId}
from Cart cart. Long message)
© Faisal Memon | EmbarkX.com

Request Request
API Name Endpoint Method Purpose Body Parameters Response

productId:
Add Adds a specified
/api/carts/products/{product Long, CartDTO
Product to POST product and quantity to None
Id}/quantity/{quantity} quantity: (JSON)
Cart the user's cart.
Integer

List of
Get All Retrieves a list of all
/api/carts GET None None CartDTO
Carts carts.
(JSON)

Get User's Retrieves the cart of CartDTO


/api/carts/users/cart GET None None
Cart the logged-in user. (JSON)

productId:
Update Updates the quantity of
/api/cart/products/{productI Long, CartDTO
Product PUT a specific product in the None
d}/quantity/{operation} operation: (JSON)
Quantity cart.
String

Delete Removes a specific cartId: Long, String


/api/carts/{cartId}/product/{
Product DELETE product from the user's None productId: (Status
productId}
from Cart cart. Long message)
© Faisal Memon | EmbarkX.com

Request Request
API Name Endpoint Method Purpose Body Parameters Response

productId:
Add Adds a specified
/api/carts/products/{product Long, CartDTO
Product to POST product and quantity to None
Id}/quantity/{quantity} quantity: (JSON)
Cart the user's cart.
Integer

List of
Get All Retrieves a list of all
/api/carts GET None None CartDTO
Carts carts.
(JSON)

Get User's Retrieves the cart of CartDTO


/api/carts/users/cart GET None None
Cart the logged-in user. (JSON)

productId:
Update Updates the quantity of
/api/cart/products/{productI Long, CartDTO
Product PUT a specific product in the None
d}/quantity/{operation} operation: (JSON)
Quantity cart.
String

Delete Removes a specific cartId: Long, String


/api/carts/{cartId}/product/{
Product DELETE product from the user's None productId: (Status
productId}
from Cart cart. Long message)
© Faisal Memon | EmbarkX.com

Request Request
API Name Endpoint Method Purpose Body Parameters Response

productId:
Add Adds a specified
/api/carts/products/{product Long, CartDTO
Product to POST product and quantity to None
Id}/quantity/{quantity} quantity: (JSON)
Cart the user's cart.
Integer

List of
Get All Retrieves a list of all
/api/carts GET None None CartDTO
Carts carts.
(JSON)

Get User's Retrieves the cart of CartDTO


/api/carts/users/cart GET None None
Cart the logged-in user. (JSON)

productId:
Update Updates the quantity of
/api/cart/products/{productI Long, CartDTO
Product PUT a specific product in the None
d}/quantity/{operation} operation: (JSON)
Quantity cart.
String

Delete Removes a specific cartId: Long, String


/api/carts/{cartId}/product/{
Product DELETE product from the user's None productId: (Status
productId}
from Cart cart. Long message)
© Faisal Memon | EmbarkX.com

Different Databases and


Magic of JPA

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Database Vendor
A database vendor is a company or organization that develops and
maintains a database management system
© Faisal Memon | EmbarkX.com

Types of Vendors

Oracle Database

MySQL

Microsoft SQL Server

PostgreSQL

MongoDB
© Faisal Memon | EmbarkX.com

Choosing the right vendor

Scale

Performance

Security

Cost

Support
© Faisal Memon | EmbarkX.com

class Category {
Long categoryId;
String categoryName;
}

categoryId categoryName

1 Senior Software Engineer


© Faisal Memon | EmbarkX.com

Advantages of using JPA


→ Easy and Simple

→ Makes querying easier

→ Allows to save and update objects

→ Easy integration with Spring Boot


© Faisal Memon | EmbarkX.com

H2 PostgreSQL MySQL

JPA Layer

Your Application Source


© Faisal Memon | EmbarkX.com

Configuration for MySQL


spring.datasource.url=jdbc:mysql://localhost:3306/ecommerce
spring.datasource.username=root
spring.datasource.password=<your-password>

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Database Schema
Management

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

spring.jpa.hibernate.ddl-auto=update
© Faisal Memon | EmbarkX.com

Possible Values
none

validate

update

create

create-drop

create-only
© Faisal Memon | EmbarkX.com

Value Description When to Use

Use this in production environments


Hibernate does not perform any schema generation
none where schema changes are managed
or modification.
manually or through migrations.

Hibernate validates the schema against the entities.


Use this in production environments to
It checks if the tables and columns in the database
validate ensure the schema matches the entity
schema match the entities. If there is a mismatch, an
mappings without making changes.
exception is thrown, and the application fails to start.

Hibernate updates the database schema to match Use this in development and testing
the entities. It adds new columns and tables as environments where you want the
update
necessary, but it does not remove or modify existing schema to evolve with the entity
columns and tables. mappings without losing data.
© Faisal Memon | EmbarkX.com

Value Description When to Use

Hibernate drops the existing schema (tables) and


Use this in development and testing
creates a new schema based on the entity
create environments where you need to start
mappings. This means that all data in the existing
with a fresh schema on every run.
tables will be lost.

Use this in unit tests or short-lived


Similar to create, but in addition, Hibernate drops
applications where you need a fresh
create-drop the schema when the SessionFactory is closed,
schema on every run and don't need to
typically when the application shuts down.
keep the data after the application ends.

Use this when you need to create the


Hibernate creates the schema, but does not drop it schema initially but want to handle
create-only
when the session factory is closed. cleanup or further management
manually.
© Faisal Memon | EmbarkX.com

Thinking About Managing


Addresses

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Request Request
API Name Endpoint Method Purpose Body Parameters Response

Create a AddressDTO with


Create AddressDT
/addresses POST new None HttpStatus.CREAT
Address O
address ED

Retrieve
Get All all List of AddressDTO
/addresses GET None None
Addresses addresse with HttpStatus.OK
s

Retrieve
Get Path:
an AddressDTO with
Address /addresses/{addressId} GET None addressId
address HttpStatus.OK
by ID (Long)
by its ID

Retrieve
Get the
AddressDTO with
Address /users/addresses GET logged-in None None
HttpStatus.OK
by User user's
address
© Faisal Memon | EmbarkX.com

Meth Request Request


API Name Endpoint od Purpose Body Parameters Response

Update an
Path:
Update existing AddressDTO with
/addresses/{addressId} PUT Address addressId
Address address by HttpStatus.OK
(Long)
its ID

Delete an Path:
Delete DELE Status message
/addresses/{addressId} address by None addressId
Address TE with HttpStatus.OK
its ID (Long)
© Faisal Memon | EmbarkX.com

Understanding Deployments

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

OUR APPLICATION
Database

REACT
Browser Controllers Services
APP Repositories

SERVER

SERVER

Response Back

Postman
© Faisal Memon | EmbarkX.com

OUR APPLICATION
Database

REACT
Browser Controllers Services
APP Repositories

SERVER
RDS
EC2

Response Back

Postman
© Faisal Memon | EmbarkX.com

OUR APPLICATION
Database

Browser Controllers Services Repositories

RDS
EC2

Response Back

Postman
© Faisal Memon | EmbarkX.com

If you think this course helped you, please do help provide an honest rating and
review of the course. Your insights help us improve and provide better content
for future learners.

We appreciate your support and look forward to hearing your thoughts!

You might also like